Django

Code

Changeset 8772

Show
Ignore:
Timestamp:
08/31/08 15:11:11 (3 months ago)
Author:
jacob
Message:

Fixed #6967: ModelForms now validate choices. Thanks, mattmcc -- the failing test helped quite a bit.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/fields/__init__.py

    r8691 r8772  
    306306        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} 
    307307        if self.choices: 
    308             defaults['widget'] = forms.Select(choices=self.get_choices(include_blank=self.blank or not (self.has_default() or 'initial' in kwargs))) 
     308            form_class = forms.TypedChoiceField 
     309            include_blank = self.blank or not (self.has_default() or 'initial' in kwargs) 
     310            defaults['choices'] = self.get_choices(include_blank=include_blank) 
     311            defaults['coerce'] = self.to_python 
     312            if self.null: 
     313                defaults['empty_value'] = None 
     314            kwargs.pop('max_length', None) 
    309315        if self.has_default(): 
    310316            defaults['initial'] = self.get_default() 
  • django/trunk/tests/modeltests/model_forms/models.py

    r8756 r8772  
    2626    (2, 'Pending'), 
    2727    (3, 'Live'), 
     28) 
     29 
     30ARTICLE_STATUS_CHAR = ( 
     31    ('d', 'Draft'), 
     32    ('p', 'Pending'), 
     33    ('l', 'Live'), 
    2834) 
    2935 
     
    111117    def __unicode__(self): 
    112118        return self.field 
     119 
     120class ArticleStatus(models.Model): 
     121    status = models.CharField(max_length=2, choices=ARTICLE_STATUS_CHAR, blank=True, null=True) 
    113122 
    114123__test__ = {'API_TESTS': """ 
     
    11241133u'1' 
    11251134 
     1135# Choices on CharField and IntegerField 
     1136 
     1137>>> class ArticleForm(ModelForm): 
     1138...     class Meta: 
     1139...         model = Article 
     1140>>> f = ArticleForm() 
     1141>>> f.fields['status'].clean('42') 
     1142Traceback (most recent call last): 
     1143... 
     1144ValidationError: [u'Select a valid choice. 42 is not one of the available choices.'] 
     1145 
     1146>>> class ArticleStatusForm(ModelForm): 
     1147...     class Meta: 
     1148...         model = ArticleStatus 
     1149>>> f = ArticleStatusForm() 
     1150>>> f.fields['status'].clean('z') 
     1151Traceback (most recent call last): 
     1152... 
     1153ValidationError: [u'Select a valid choice. z is not one of the available choices.'] 
     1154 
    11261155"""}