Code

Ticket #5335: append-take3-r9698.diff

File append-take3-r9698.diff, 4.3 KB (added by kratorius, 5 years ago)

Fixed patch, create an ErrorList instead of a simple list

Line 
1Index: django/forms/util.py
2===================================================================
3--- django/forms/util.py        (revision 9699)
4+++ django/forms/util.py        (working copy)
5@@ -29,6 +29,9 @@
6     def as_text(self):
7         return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u'  * %s' % force_unicode(i) for i in v])) for k, v in self.items()])
8 
9+    def __getitem__(self, field):
10+        return self.setdefault(field, ErrorList())
11+
12 class ErrorList(list, StrAndUnicode):
13     """
14     A collection of errors that knows how to display itself in various formats.
15Index: tests/regressiontests/forms/forms.py
16===================================================================
17--- tests/regressiontests/forms/forms.py        (revision 9699)
18+++ tests/regressiontests/forms/forms.py        (working copy)
19@@ -707,6 +707,29 @@
20 >>> f.cleaned_data['password2']
21 u'foo'
22 
23+Test that you can append errors to a field in the clean() method of a Form. This way you
24+can place the error message using a shorter syntax (i.e.: self._errors['fieldname'].append(u'error message'))
25+>>> class AppendErrors(Form):
26+...    field1 = IntegerField()
27+...    field2 = IntegerField()
28+...    def clean(self):
29+...        if self.cleaned_data['field1'] <= self.cleaned_data['field2']:
30+...            self._errors['field1'].append(u"Field1 can't be greater than Field2!")
31+...        return self.cleaned_data
32+>>> f = AppendErrors()
33+>>> f.errors
34+{}
35+>>> f.errors['field1']
36+[]
37+>>> f = AppendErrors({'field1': 5, 'field2': 10})
38+>>> f.errors
39+{'field1': [u"Field1 can't be greater than Field2!"]}
40+>>> f.errors['field1']
41+[u"Field1 can't be greater than Field2!"]
42+>>> f.errors['field2']
43+[]
44+
45+
46 # Dynamic construction ########################################################
47 
48 It's possible to construct a Form dynamically by adding to the self.fields
49Index: docs/ref/forms/validation.txt
50===================================================================
51--- docs/ref/forms/validation.txt       (revision 9699)
52+++ docs/ref/forms/validation.txt       (working copy)
53@@ -107,11 +107,11 @@
54 display itself in different ways. So you can treat ``_errors`` as a dictionary
55 mapping field names to lists.
56 
57-If you want to add a new error to a particular field, you should check whether
58-the key already exists in ``self._errors`` or not. If not, create a new entry
59-for the given key, holding an empty ``ErrorList`` instance. In either case,
60-you can then append your error message to the list for the field name in
61-question and it will be displayed when the form is displayed.
62+If you want to add a new error to a particular field, you can append your error
63+message to the list for the field name in question by using ``append()``.
64+Django will check if the key already exists, otherwise it will create an empty
65+``ErrorList`` instance. Then the error message will be displayed when the form
66+is displayed.
67 
68 There is an example of modifying ``self._errors`` in the following section.
69 
70@@ -272,11 +272,9 @@
71             subject = cleaned_data.get("subject")
72 
73             if cc_myself and subject and "help" not in subject:
74-                # We know these are not in self._errors now (see discussion
75-                # below).
76                 msg = u"Must put 'help' in subject when cc'ing yourself."
77-                self._errors["cc_myself"] = ErrorList([msg])
78-                self._errors["subject"] = ErrorList([msg])
79+                self._errors["cc_myself"].append(msg)
80+                self._errors["subject"].append(msg)
81 
82                 # These fields are no longer valid. Remove them from the
83                 # cleaned data.
84@@ -288,11 +286,9 @@
85 
86 As you can see, this approach requires a bit more effort, not withstanding the
87 extra design effort to create a sensible form display. The details are worth
88-noting, however. Firstly, earlier we mentioned that you might need to check if
89-the field name keys already exist in the ``_errors`` dictionary. In this case,
90-since we know the fields exist in ``self.cleaned_data``, they must have been
91-valid when cleaned as individual fields, so there will be no corresponding
92-entries in ``_errors``.
93+noting, however. Firstly, we mentioned that in order to add errors to the
94+fields, you just need to ``append()`` your error message in the ``_errors``
95+dictionary.
96 
97 Secondly, once we have decided that the combined data in the two fields we are
98 considering aren't valid, we must remember to remove them from the