Code

Ticket #8913: unique-error-message-with-docs.diff

File unique-error-message-with-docs.diff, 4.6 KB (added by leahculver, 3 years ago)

Added documentation.

Line 
1Index: docs/ref/models/fields.txt
2===================================================================
3--- docs/ref/models/fields.txt  (revision 16341)
4+++ docs/ref/models/fields.txt  (working copy)
5@@ -210,6 +210,10 @@
6 field will raise. Pass in a dictionary with keys matching the error messages you
7 want to override.
8 
9+Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
10+and ``unique``. Additional error message keys are specified for each field in
11+the `Field types`_ section below.
12+
13 ``help_text``
14 -------------
15 
16@@ -416,7 +420,8 @@
17     it's not just a default value that you can override.
18 
19 The admin represents this as an ``<input type="text">`` with a JavaScript
20-calendar, and a shortcut for "Today".
21+calendar, and a shortcut for "Today". Includes an additional ``invalid_date``
22+error message key.
23 
24 .. note::
25     As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
26Index: tests/modeltests/validation/models.py
27===================================================================
28--- tests/modeltests/validation/models.py       (revision 16341)
29+++ tests/modeltests/validation/models.py       (working copy)
30@@ -78,3 +78,7 @@
31     slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
32     subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
33     posted = models.DateField(blank=True, null=True)
34+
35+class UniqueErrorsModel(models.Model):
36+    name = models.CharField(max_length=100, unique=True, error_messages={'unique': u'Custom unique name message.'})
37+    number = models.IntegerField(unique=True, error_messages={'unique': u'Custom unique number message.'})
38\ No newline at end of file
39Index: tests/modeltests/validation/test_unique.py
40===================================================================
41--- tests/modeltests/validation/test_unique.py  (revision 16341)
42+++ tests/modeltests/validation/test_unique.py  (working copy)
43@@ -7,7 +7,7 @@
44 from django.utils import unittest
45 
46 from models import (CustomPKModel, UniqueTogetherModel, UniqueFieldsModel,
47-    UniqueForDateModel, ModelToValidate, Post, FlexibleDatePost)
48+    UniqueForDateModel, ModelToValidate, Post, FlexibleDatePost, UniqueErrorsModel)
49 
50 
51 class GetUniqueCheckTests(unittest.TestCase):
52@@ -149,3 +149,22 @@
53             self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.")
54         except:
55             self.fail("unique_for_month checks shouldn't explode when the associated DateField is None.")
56+
57+    def test_unique_errors(self):
58+        m1 = UniqueErrorsModel.objects.create(name='Some Name', number=10)
59+        m = UniqueErrorsModel(name='Some Name', number=11)
60+        try:
61+            m.full_clean()
62+        except ValidationError, e:
63+            self.assertEqual(e.message_dict, {'name': [u'Custom unique name message.']})
64+        except:
65+            self.fail('unique checks should catch this.')
66+
67+        m = UniqueErrorsModel(name='Some Other Name', number=10)
68+        try:
69+            m.full_clean()
70+        except ValidationError, e:
71+            self.assertEqual(e.message_dict, {'number': [u'Custom unique number message.']})
72+        except:
73+            self.fail('unique checks should catch this.')
74+           
75\ No newline at end of file
76Index: django/db/models/base.py
77===================================================================
78--- django/db/models/base.py    (revision 16341)
79+++ django/db/models/base.py    (working copy)
80@@ -782,9 +782,10 @@
81         # A unique field
82         if len(unique_check) == 1:
83             field_name = unique_check[0]
84-            field_label = capfirst(opts.get_field(field_name).verbose_name)
85+            field = opts.get_field(field_name)
86+            field_label = capfirst(field.verbose_name)
87             # Insert the error into the error dict, very sneaky
88-            return _(u"%(model_name)s with this %(field_label)s already exists.") %  {
89+            return field.error_messages['unique'] %  {
90                 'model_name': unicode(model_name),
91                 'field_label': unicode(field_label)
92             }
93Index: django/db/models/fields/__init__.py
94===================================================================
95--- django/db/models/fields/__init__.py (revision 16341)
96+++ django/db/models/fields/__init__.py (working copy)
97@@ -60,6 +60,7 @@
98         'invalid_choice': _(u'Value %r is not a valid choice.'),
99         'null': _(u'This field cannot be null.'),
100         'blank': _(u'This field cannot be blank.'),
101+        'unique': _(u'%(model_name)s with this %(field_label)s already exists.'),
102     }
103 
104     # Generic field type description, usually overriden by subclasses