1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Fixed #26970 -- Fixed crash with disabled ModelMultipleChoiceField.

This commit is contained in:
Tim Graham 2016-07-30 10:13:10 -04:00
parent 36fbf9b7d1
commit 4e86168290
2 changed files with 26 additions and 0 deletions

View File

@ -1251,6 +1251,7 @@ class ModelMultipleChoiceField(ModelChoiceField):
return list(self._check_values(value))
def clean(self, value):
value = self.prepare_value(value)
if self.required and not value:
raise ValidationError(self.error_messages['required'], code='required')
elif not self.required and not value:

View File

@ -1534,6 +1534,31 @@ class ModelChoiceFieldTests(TestCase):
['Select a valid choice. That choice is not one of the available choices.']
)
def test_disabled_multiplemodelchoicefield(self):
class ArticleForm(forms.ModelForm):
categories = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
class Meta:
model = Article
fields = ['categories']
category1 = Category.objects.create(name='cat1')
category2 = Category.objects.create(name='cat2')
article = Article.objects.create(
pub_date=datetime.date(1988, 1, 4),
writer=Writer.objects.create(name='Test writer'),
)
article.categories.set([category1.pk])
form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
self.assertEqual(form.errors, {})
self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category2.pk])
# Disabled fields use the value from `instance` rather than `data`.
form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
form.fields['categories'].disabled = True
self.assertEqual(form.errors, {})
self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category1.pk])
def test_modelchoicefield_iterator(self):
"""
Iterator defaults to ModelChoiceIterator and can be overridden with