Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #8913 - Make "must be unique" error messages customisable. Than…

…ks to Leah Culver.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16345 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 865d684a8af8e3ef7a11c43df861e1a69b0d8cd4 1 parent 7f6675a
Andrew Godwin authored June 09, 2011
2  AUTHORS
@@ -128,7 +128,7 @@ answer newbie questions, and generally made Django that much better:
128 128
     Robert Coup
129 129
     Pete Crosier <pete.crosier@gmail.com>
130 130
     Matt Croydon <http://www.postneo.com/>
131  
-    Leah Culver <leah@pownce.com>
  131
+    Leah Culver <leah.culver@gmail.com>
132 132
     flavio.curella@gmail.com
133 133
     Jure Cuhalev <gandalf@owca.info>
134 134
     John D'Agostino <john.dagostino@gmail.com>
5  django/db/models/base.py
@@ -782,9 +782,10 @@ def unique_error_message(self, model_class, unique_check):
782 782
         # A unique field
783 783
         if len(unique_check) == 1:
784 784
             field_name = unique_check[0]
785  
-            field_label = capfirst(opts.get_field(field_name).verbose_name)
  785
+            field = opts.get_field(field_name)
  786
+            field_label = capfirst(field.verbose_name)
786 787
             # Insert the error into the error dict, very sneaky
787  
-            return _(u"%(model_name)s with this %(field_label)s already exists.") %  {
  788
+            return field.error_messages['unique'] %  {
788 789
                 'model_name': unicode(model_name),
789 790
                 'field_label': unicode(field_label)
790 791
             }
1  django/db/models/fields/__init__.py
@@ -60,6 +60,7 @@ class Field(object):
60 60
         'invalid_choice': _(u'Value %r is not a valid choice.'),
61 61
         'null': _(u'This field cannot be null.'),
62 62
         'blank': _(u'This field cannot be blank.'),
  63
+        'unique': _(u'%(model_name)s with this %(field_label)s already exists.'),
63 64
     }
64 65
 
65 66
     # Generic field type description, usually overriden by subclasses
7  docs/ref/models/fields.txt
@@ -210,6 +210,10 @@ The ``error_messages`` argument lets you override the default messages that the
210 210
 field will raise. Pass in a dictionary with keys matching the error messages you
211 211
 want to override.
212 212
 
  213
+Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
  214
+and ``unique``. Additional error message keys are specified for each field in
  215
+the `Field types`_ section below.
  216
+
213 217
 ``help_text``
214 218
 -------------
215 219
 
@@ -416,7 +420,8 @@ optional arguments:
416 420
     it's not just a default value that you can override.
417 421
 
418 422
 The admin represents this as an ``<input type="text">`` with a JavaScript
419  
-calendar, and a shortcut for "Today".
  423
+calendar, and a shortcut for "Today". Includes an additional ``invalid_date``
  424
+error message key.
420 425
 
421 426
 .. note::
422 427
     As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
4  tests/modeltests/validation/models.py
@@ -78,3 +78,7 @@ class FlexibleDatePost(models.Model):
78 78
     slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
79 79
     subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
80 80
     posted = models.DateField(blank=True, null=True)
  81
+
  82
+class UniqueErrorsModel(models.Model):
  83
+    name = models.CharField(max_length=100, unique=True, error_messages={'unique': u'Custom unique name message.'})
  84
+    number = models.IntegerField(unique=True, error_messages={'unique': u'Custom unique number message.'})
21  tests/modeltests/validation/test_unique.py
@@ -7,7 +7,7 @@
7 7
 from django.utils import unittest
8 8
 
9 9
 from models import (CustomPKModel, UniqueTogetherModel, UniqueFieldsModel,
10  
-    UniqueForDateModel, ModelToValidate, Post, FlexibleDatePost)
  10
+    UniqueForDateModel, ModelToValidate, Post, FlexibleDatePost, UniqueErrorsModel)
11 11
 
12 12
 
13 13
 class GetUniqueCheckTests(unittest.TestCase):
@@ -149,3 +149,22 @@ def test_unique_for_date_with_nullable_date(self):
149 149
             self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.")
150 150
         except:
151 151
             self.fail("unique_for_month checks shouldn't explode when the associated DateField is None.")
  152
+
  153
+    def test_unique_errors(self):
  154
+        m1 = UniqueErrorsModel.objects.create(name='Some Name', number=10)
  155
+        m = UniqueErrorsModel(name='Some Name', number=11)
  156
+        try:
  157
+            m.full_clean()
  158
+        except ValidationError, e:
  159
+            self.assertEqual(e.message_dict, {'name': [u'Custom unique name message.']})
  160
+        except:
  161
+            self.fail('unique checks should catch this.')
  162
+
  163
+        m = UniqueErrorsModel(name='Some Other Name', number=10)
  164
+        try:
  165
+            m.full_clean()
  166
+        except ValidationError, e:
  167
+            self.assertEqual(e.message_dict, {'number': [u'Custom unique number message.']})
  168
+        except:
  169
+            self.fail('unique checks should catch this.')
  170
+            

0 notes on commit 865d684

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