# HG changeset patch
# User Petr Marhoun <petr.marhoun@gmail.com>
# Date 1262727798 -3600
# Node ID 808774980dda1222ec10360e2fd53dc994402342
# Parent 905311cd1716f58b994115cf5a782de20bf536c7
[mq]: django-model-choice-field-validation.diff
diff --git a/django/forms/models.py b/django/forms/models.py
|
a
|
b
|
|
| 875 | 875 | |
| 876 | 876 | choices = property(_get_choices, ChoiceField._set_choices) |
| 877 | 877 | |
| 878 | | def clean(self, value): |
| 879 | | Field.clean(self, value) |
| | 878 | def to_python(self, value): |
| 880 | 879 | if value in EMPTY_VALUES: |
| 881 | 880 | return None |
| 882 | 881 | try: |
| … |
… |
|
| 886 | 885 | raise ValidationError(self.error_messages['invalid_choice']) |
| 887 | 886 | return value |
| 888 | 887 | |
| | 888 | def validate(self, value): |
| | 889 | return Field.validate(self, value) |
| | 890 | |
| 889 | 891 | class ModelMultipleChoiceField(ModelChoiceField): |
| 890 | 892 | """A MultipleChoiceField whose choices are a model QuerySet.""" |
| 891 | 893 | widget = SelectMultiple |
diff --git a/tests/regressiontests/forms/models.py b/tests/regressiontests/forms/models.py
|
a
|
b
|
|
| 41 | 41 | class FileForm(django_forms.Form): |
| 42 | 42 | file1 = django_forms.FileField() |
| 43 | 43 | |
| | 44 | class Group(models.Model): |
| | 45 | name = models.CharField(max_length=10) |
| | 46 | |
| | 47 | def __unicode__(self): |
| | 48 | return self.name |
| | 49 | |
| | 50 | class SubGroup(models.Model): |
| | 51 | group = models.ForeignKey(Group) |
| | 52 | name = models.CharField(max_length=10) |
| | 53 | |
| | 54 | def __unicode__(self): |
| | 55 | return u'%s - %s' % (self.group.name, self.name) |
| | 56 | |
| 44 | 57 | __test__ = {'API_TESTS': """ |
| 45 | 58 | >>> from django.forms.models import ModelForm |
| 46 | 59 | >>> from django.core.files.uploadedfile import SimpleUploadedFile |
| … |
… |
|
| 131 | 144 | >>> list(ChoiceFieldForm().fields['choice'].choices) |
| 132 | 145 | [(1, u'ChoiceOptionModel object')] |
| 133 | 146 | |
| | 147 | It is not necessary to generate choices for ModelChoiceField (regression test for #12510). |
| | 148 | |
| | 149 | >>> group = Group.objects.create(name='test') |
| | 150 | >>> subgroups = [SubGroup.objects.create(group=group, name=name) for name in 'abcdefghij'] |
| | 151 | |
| | 152 | >>> from django.conf import settings |
| | 153 | >>> from django import db |
| | 154 | |
| | 155 | >>> settings.DEBUG = True |
| | 156 | >>> db.reset_queries() |
| | 157 | |
| | 158 | >>> field = django_forms.ModelChoiceField(SubGroup.objects.order_by('-name')) |
| | 159 | >>> field.clean(subgroups[0].pk).name |
| | 160 | u'a' |
| | 161 | >>> len(db.connection.queries) |
| | 162 | 1 |
| | 163 | |
| | 164 | >>> settings.DEBUG = False |
| | 165 | |
| 134 | 166 | """} |