Code

Ticket #5335: form_error_append.diff

File form_error_append.diff, 1.5 KB (added by Thomas Güttler <hv@…>, 7 years ago)
Line 
1Index: docs/newforms.txt
2===================================================================
3--- docs/newforms.txt   (Revision 6046)
4+++ docs/newforms.txt   (Arbeitskopie)
5@@ -1387,6 +1387,12 @@
6       "field" (called ``__all__``, which you can access via the
7       ``non_field_errors()`` method if you need to.
8 
9+
10+      Instead of raising an ValidationError inside ``Form.clean()``,
11+      you can add an error message with
12+      ``self.errors.append(fieldname, message)``. This way the error message
13+      will be displayed near the given field.
14+
15 These methods are run in the order given above, one field at a time.  That is,
16 for each field in the form (in the order they are declared in the form
17 definition), the ``Field.clean()`` method (or it's override) is run, then
18Index: django/newforms/util.py
19===================================================================
20--- django/newforms/util.py     (Revision 6046)
21+++ django/newforms/util.py     (Arbeitskopie)
22@@ -26,6 +26,13 @@
23     def as_text(self):
24         return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u'  * %s' % smart_unicode(i) for i in v])) for k, v in self.items()])
25 
26+    def append(self, name, message):
27+        errorlist=self.get(name)
28+        if errorlist==None:
29+            errorlist=ErrorList()
30+            self[name]=errorlist
31+        errorlist.append(message)
32+           
33 class ErrorList(list, StrAndUnicode):
34     """
35     A collection of errors that knows how to display itself in various formats.