diff --git a/django/forms/models.py b/django/forms/models.py
index 2a3f8bd..912bdf3 100644
a
|
b
|
class ModelMultipleChoiceField(ModelChoiceField):
|
1006 | 1006 | return [] |
1007 | 1007 | if not isinstance(value, (list, tuple)): |
1008 | 1008 | raise ValidationError(self.error_messages['list']) |
| 1009 | key = self.to_field_name or 'pk' |
1009 | 1010 | for pk in value: |
1010 | 1011 | try: |
1011 | | self.queryset.filter(pk=pk) |
| 1012 | self.queryset.filter(**{key: pk}) |
1012 | 1013 | except ValueError: |
1013 | 1014 | 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]) |
1016 | 1017 | for val in value: |
1017 | 1018 | if force_unicode(val) not in pks: |
1018 | 1019 | raise ValidationError(self.error_messages['invalid_choice'] % val) |
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
|
1562 | 1562 | <tr><th><label for="id_description">Description:</label></th><td><input type="text" name="description" id="id_description" /></td></tr> |
1563 | 1563 | <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr> |
1564 | 1564 | |
| 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() |
| 1580 | True |
| 1581 | >>> form.cleaned_data |
| 1582 | {'items': [<Inventory: Pear>, <Inventory: Core>]} |
| 1583 | |
1565 | 1584 | # Model field that returns None to exclude itself with explicit fields ######## |
1566 | 1585 | |
1567 | 1586 | >>> class CustomFieldForExclusionForm(ModelForm): |