Ticket #9161: 9161-against-9072.diff

File 9161-against-9072.diff, 1.9 KB (added by Honza Král, 16 years ago)
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 6024a1c..6e043ff 100644
    a b class ModelMultipleChoiceField(ModelChoiceField):  
    664664
    665665    def __init__(self, queryset, cache_choices=False, required=True,
    666666                 widget=None, label=None, initial=None,
    667                  help_text=None, *args, **kwargs):
     667                 help_text=None, to_field_name=None, *args, **kwargs):
    668668        super(ModelMultipleChoiceField, self).__init__(queryset, None,
    669669            cache_choices, required, widget, label, initial, help_text,
    670             *args, **kwargs)
     670            to_field_name, *args, **kwargs)
    671671
    672672    def clean(self, value):
    673673        if self.required and not value:
    class ModelMultipleChoiceField(ModelChoiceField):  
    679679        final_values = []
    680680        for val in value:
    681681            try:
    682                 obj = self.queryset.get(pk=val)
     682                key = self.to_field_name or 'pk'
     683                obj = self.queryset.get(**{key: val})
    683684            except self.queryset.model.DoesNotExist:
    684685                raise ValidationError(self.error_messages['invalid_choice'] % val)
    685686            else:
  • tests/modeltests/model_forms/models.py

    diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py
    index e3821de..21a1a33 100644
    a b ValidationError: [u'Select a valid choice. z is not one of the available choices  
    12321232(86, u'Apple')
    12331233(22, u'Pear')
    12341234(87, u'Core')
     1235>>> field.clean(u'87')
     1236<Inventory: Core>
     1237
     1238>>> field = ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
     1239>>> for choice in field.choices:
     1240...     print choice
     1241(86, u'Apple')
     1242(22, u'Pear')
     1243(87, u'Core')
     1244>>> field.clean([u'86',u'22'])
     1245[<Inventory: Apple>, <Inventory: Pear>]
    12351246
    12361247>>> class InventoryForm(ModelForm):
    12371248...     class Meta:
Back to Top