Django

Code

Changeset 6694

Show
Ignore:
Timestamp:
11/18/07 14:25:23 (10 months ago)
Author:
gwilson
Message:

Fixed #5975 -- Gave ModelChoiceField and ModelMultipleChoiceField ability to specify custom error messages.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/newforms/models.py

    r6670 r6694  
    44""" 
    55 
    6 from django.utils.translation import ugettext 
     6from django.utils.translation import ugettext_lazy as _ 
    77from django.utils.encoding import smart_unicode 
    88from django.utils.datastructures import SortedDict 
     
    152152    # This class is a subclass of ChoiceField for purity, but it doesn't 
    153153    # actually use any of ChoiceField's implementation. 
     154    default_error_messages = { 
     155        'invalid_choice': _(u'Select a valid choice. That choice is not one of' 
     156                            u' the available choices.'), 
     157    } 
    154158 
    155159    def __init__(self, queryset, empty_label=u"---------", cache_choices=False, 
    156160                 required=True, widget=Select, label=None, initial=None, 
    157                  help_text=None): 
     161                 help_text=None, *args, **kwargs): 
    158162        self.empty_label = empty_label 
    159163        self.cache_choices = cache_choices 
    160164        # Call Field instead of ChoiceField __init__() because we don't need 
    161165        # ChoiceField.__init__(). 
    162         Field.__init__(self, required, widget, label, initial, help_text) 
     166        Field.__init__(self, required, widget, label, initial, help_text, 
     167                       *args, **kwargs) 
    163168        self.queryset = queryset 
    164169 
     
    201206            value = self.queryset.get(pk=value) 
    202207        except self.queryset.model.DoesNotExist: 
    203             raise ValidationError(ugettext(u'Select a valid choice. That' 
    204                                            u' choice is not one of the' 
    205                                            u' available choices.')) 
     208            raise ValidationError(self.error_messages['invalid_choice']) 
    206209        return value 
    207210 
     
    209212    """A MultipleChoiceField whose choices are a model QuerySet.""" 
    210213    hidden_widget = MultipleHiddenInput 
     214    default_error_messages = { 
     215        'list': _(u'Enter a list of values.'), 
     216        'invalid_choice': _(u'Select a valid choice. %s is not one of the' 
     217                            u' available choices.'), 
     218    } 
    211219 
    212220    def __init__(self, queryset, cache_choices=False, required=True, 
    213221                 widget=SelectMultiple, label=None, initial=None, 
    214                  help_text=None): 
     222                 help_text=None, *args, **kwargs): 
    215223        super(ModelMultipleChoiceField, self).__init__(queryset, None, 
    216             cache_choices, required, widget, label, initial, help_text) 
     224            cache_choices, required, widget, label, initial, help_text, 
     225            *args, **kwargs) 
    217226 
    218227    def clean(self, value): 
    219228        if self.required and not value: 
    220             raise ValidationError(ugettext(u'This field is required.')
     229            raise ValidationError(self.error_messages['required']
    221230        elif not self.required and not value: 
    222231            return [] 
    223232        if not isinstance(value, (list, tuple)): 
    224             raise ValidationError(ugettext(u'Enter a list of values.')
     233            raise ValidationError(self.error_messages['list']
    225234        final_values = [] 
    226235        for val in value: 
     
    228237                obj = self.queryset.get(pk=val) 
    229238            except self.queryset.model.DoesNotExist: 
    230                 raise ValidationError(ugettext(u'Select a valid choice. %s is' 
    231                                                u' not one of the available' 
    232                                                u' choices.') % val) 
     239                raise ValidationError(self.error_messages['invalid_choice'] % val) 
    233240            else: 
    234241                final_values.append(obj) 
  • django/trunk/tests/regressiontests/forms/error_messages.py

    r6625 r6694  
    313313... 
    314314ValidationError: [u'INVALID IP ADDRESS'] 
     315 
     316############################################################################### 
     317 
     318# Create choices for the model choice field tests below. 
     319 
     320>>> from regressiontests.forms.models import ChoiceModel 
     321>>> ChoiceModel.objects.create(pk=1, name='a') 
     322<ChoiceModel: ChoiceModel object> 
     323>>> ChoiceModel.objects.create(pk=2, name='b') 
     324<ChoiceModel: ChoiceModel object> 
     325>>> ChoiceModel.objects.create(pk=3, name='c') 
     326<ChoiceModel: ChoiceModel object> 
     327 
     328# ModelChoiceField ############################################################ 
     329 
     330>>> e = {'required': 'REQUIRED'} 
     331>>> e['invalid_choice'] = 'INVALID CHOICE' 
     332>>> f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) 
     333>>> f.clean('') 
     334Traceback (most recent call last): 
     335... 
     336ValidationError: [u'REQUIRED'] 
     337>>> f.clean('4') 
     338Traceback (most recent call last): 
     339... 
     340ValidationError: [u'INVALID CHOICE'] 
     341 
     342# ModelMultipleChoiceField #################################################### 
     343 
     344>>> e = {'required': 'REQUIRED'} 
     345>>> e['invalid_choice'] = '%s IS INVALID CHOICE' 
     346>>> e['list'] = 'NOT A LIST OF VALUES' 
     347>>> f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) 
     348>>> f.clean('') 
     349Traceback (most recent call last): 
     350... 
     351ValidationError: [u'REQUIRED'] 
     352>>> f.clean('3') 
     353Traceback (most recent call last): 
     354... 
     355ValidationError: [u'NOT A LIST OF VALUES'] 
     356>>> f.clean(['4']) 
     357Traceback (most recent call last): 
     358... 
     359ValidationError: [u'4 IS INVALID CHOICE'] 
    315360""" 
  • django/trunk/tests/regressiontests/forms/models.py

    r6595 r6694  
    1010    def_date = models.DateField(default = datetime.date(1980, 1, 1)) 
    1111    value = models.IntegerField(default=42) 
     12 
     13class ChoiceModel(models.Model): 
     14    """For ModelChoiceField and ModelMultipleChoiceField tests.""" 
     15    name = models.CharField(max_length=10) 
    1216 
    1317__test__ = {'API_TESTS': """