Ticket #12510: django-model-choice-field-validation.2.diff

File django-model-choice-field-validation.2.diff, 2.3 KB (added by Petr Marhoun <petr.marhoun@…>, 14 years ago)
  • django/forms/models.py

    # 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  
    875875
    876876    choices = property(_get_choices, ChoiceField._set_choices)
    877877
    878     def clean(self, value):
    879         Field.clean(self, value)
     878    def to_python(self, value):
    880879        if value in EMPTY_VALUES:
    881880            return None
    882881        try:
     
    886885            raise ValidationError(self.error_messages['invalid_choice'])
    887886        return value
    888887
     888    def validate(self, value):
     889        return Field.validate(self, value)
     890
    889891class ModelMultipleChoiceField(ModelChoiceField):
    890892    """A MultipleChoiceField whose choices are a model QuerySet."""
    891893    widget = SelectMultiple
  • tests/regressiontests/forms/models.py

    diff --git a/tests/regressiontests/forms/models.py b/tests/regressiontests/forms/models.py
    a b  
    4141class FileForm(django_forms.Form):
    4242    file1 = django_forms.FileField()
    4343
     44class Group(models.Model):
     45    name = models.CharField(max_length=10)
     46
     47    def __unicode__(self):
     48        return self.name
     49
     50class 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
    4457__test__ = {'API_TESTS': """
    4558>>> from django.forms.models import ModelForm
    4659>>> from django.core.files.uploadedfile import SimpleUploadedFile
     
    131144>>> list(ChoiceFieldForm().fields['choice'].choices)
    132145[(1, u'ChoiceOptionModel object')]
    133146
     147It 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
     160u'a'
     161>>> len(db.connection.queries)
     1621
     163
     164>>> settings.DEBUG = False
     165
    134166"""}
Back to Top