Ticket #9161: issue9161.2.diff

File issue9161.2.diff, 2.3 KB (added by Gregor Müllegger, 14 years ago)

against r15330

  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 2a3f8bd..912bdf3 100644
    a b class ModelMultipleChoiceField(ModelChoiceField):  
    10061006            return []
    10071007        if not isinstance(value, (list, tuple)):
    10081008            raise ValidationError(self.error_messages['list'])
     1009        key = self.to_field_name or 'pk'
    10091010        for pk in value:
    10101011            try:
    1011                 self.queryset.filter(pk=pk)
     1012                self.queryset.filter(**{key: pk})
    10121013            except ValueError:
    10131014                raise ValidationError(self.error_messages['invalid_pk_value'] % pk)
    1014         qs = self.queryset.filter(pk__in=value)
    1015         pks = set([force_unicode(o.pk) for o in qs])
     1015        qs = self.queryset.filter(**{'%s__in' % key: value})
     1016        pks = set([force_unicode(getattr(o, key)) for o in qs])
    10161017        for val in value:
    10171018            if force_unicode(val) not in pks:
    10181019                raise ValidationError(self.error_messages['invalid_choice'] % val)
  • tests/modeltests/model_forms/models.py

    diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py
    index b9b8d16..ad86302 100644
    a b ValidationError: [u'Select a valid choice. z is not one of the available choices  
    15621562<tr><th><label for="id_description">Description:</label></th><td><input type="text" name="description" id="id_description" /></td></tr>
    15631563<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
    15641564
     1565# to_field_name should also work on ModelMultipleChoiceField ##################
     1566
     1567>>> field = ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
     1568>>> for choice in field.choices:
     1569...     print choice
     1570(86, u'Apple')
     1571(22, u'Pear')
     1572(87, u'Core')
     1573>>> field.clean(86)
     1574<Inventory: Apple>
     1575
     1576>>> class SelectInventoryForm(forms.Form):
     1577...     items = ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
     1578>>> form = SelectInventoryForm({'items': [87, 22]})
     1579>>> form.is_valid()
     1580True
     1581>>> form.cleaned_data
     1582{'items': [<Inventory: Pear>, <Inventory: Core>]}
     1583
    15651584# Model field that returns None to exclude itself with explicit fields ########
    15661585
    15671586>>> class CustomFieldForExclusionForm(ModelForm):
Back to Top