Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #5975 -- Gave `ModelChoiceField` and `ModelMultipleChoiceField`…

… ability to specify custom error messages.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@6694 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit b2b6fc8e3c78671c8b6af2709358c3213c84d119 1 parent 86ca11d
Gary Wilson Jr. authored November 18, 2007
33  django/newforms/models.py
@@ -3,7 +3,7 @@
3 3
 and database field objects.
4 4
 """
5 5
 
6  
-from django.utils.translation import ugettext
  6
+from django.utils.translation import ugettext_lazy as _
7 7
 from django.utils.encoding import smart_unicode
8 8
 from django.utils.datastructures import SortedDict
9 9
 
@@ -151,15 +151,20 @@ class ModelChoiceField(ChoiceField):
151 151
     """A ChoiceField whose choices are a model QuerySet."""
152 152
     # This class is a subclass of ChoiceField for purity, but it doesn't
153 153
     # 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
+    }
154 158
 
155 159
     def __init__(self, queryset, empty_label=u"---------", cache_choices=False,
156 160
                  required=True, widget=Select, label=None, initial=None,
157  
-                 help_text=None):
  161
+                 help_text=None, *args, **kwargs):
158 162
         self.empty_label = empty_label
159 163
         self.cache_choices = cache_choices
160 164
         # Call Field instead of ChoiceField __init__() because we don't need
161 165
         # 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)
163 168
         self.queryset = queryset
164 169
 
165 170
     def _get_queryset(self):
@@ -200,36 +205,38 @@ def clean(self, value):
200 205
         try:
201 206
             value = self.queryset.get(pk=value)
202 207
         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'])
206 209
         return value
207 210
 
208 211
 class ModelMultipleChoiceField(ModelChoiceField):
209 212
     """A MultipleChoiceField whose choices are a model QuerySet."""
210 213
     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
+    }
211 219
 
212 220
     def __init__(self, queryset, cache_choices=False, required=True,
213 221
                  widget=SelectMultiple, label=None, initial=None,
214  
-                 help_text=None):
  222
+                 help_text=None, *args, **kwargs):
215 223
         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)
217 226
 
218 227
     def clean(self, value):
219 228
         if self.required and not value:
220  
-            raise ValidationError(ugettext(u'This field is required.'))
  229
+            raise ValidationError(self.error_messages['required'])
221 230
         elif not self.required and not value:
222 231
             return []
223 232
         if not isinstance(value, (list, tuple)):
224  
-            raise ValidationError(ugettext(u'Enter a list of values.'))
  233
+            raise ValidationError(self.error_messages['list'])
225 234
         final_values = []
226 235
         for val in value:
227 236
             try:
228 237
                 obj = self.queryset.get(pk=val)
229 238
             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)
233 240
             else:
234 241
                 final_values.append(obj)
235 242
         return final_values
45  tests/regressiontests/forms/error_messages.py
@@ -312,4 +312,49 @@
312 312
 Traceback (most recent call last):
313 313
 ...
314 314
 ValidationError: [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('')
  334
+Traceback (most recent call last):
  335
+...
  336
+ValidationError: [u'REQUIRED']
  337
+>>> f.clean('4')
  338
+Traceback (most recent call last):
  339
+...
  340
+ValidationError: [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('')
  349
+Traceback (most recent call last):
  350
+...
  351
+ValidationError: [u'REQUIRED']
  352
+>>> f.clean('3')
  353
+Traceback (most recent call last):
  354
+...
  355
+ValidationError: [u'NOT A LIST OF VALUES']
  356
+>>> f.clean(['4'])
  357
+Traceback (most recent call last):
  358
+...
  359
+ValidationError: [u'4 IS INVALID CHOICE']
315 360
 """
4  tests/regressiontests/forms/models.py
@@ -10,6 +10,10 @@ class Defaults(models.Model):
10 10
     def_date = models.DateField(default = datetime.date(1980, 1, 1))
11 11
     value = models.IntegerField(default=42)
12 12
 
  13
+class ChoiceModel(models.Model):
  14
+    """For ModelChoiceField and ModelMultipleChoiceField tests."""
  15
+    name = models.CharField(max_length=10)
  16
+
13 17
 __test__ = {'API_TESTS': """
14 18
 >>> from django.newforms import form_for_model, form_for_instance
15 19
 

0 notes on commit b2b6fc8

Please sign in to comment.
Something went wrong with that request. Please try again.