Ticket #5335: form_error_append2.diff

File form_error_append2.diff, 2.6 KB (added by Thomas Güttler <hv@…>, 17 years ago)
  • tests/regressiontests/forms/forms.py

     
    16031603<p><label>Password (again): <input type="password" name="password2" value="bar" /></label></p>
    16041604<input type="submit" />
    16051605</form>
     1606
     1607Test that you can append errors in the clean() method of a Form. This way you can place
     1608the error message near a real Field (and not __all__)
     1609>>> class StartEnd(Form):
     1610...     start = IntegerField()
     1611...     end = IntegerField()
     1612...     def clean(self):
     1613...         start, end = self.cleaned_data.get('start'), self.cleaned_data.get('end')
     1614...         if start!=None and end!=None and start>end:
     1615...             self.errors.append('start', u'start must be smaller than end')
     1616...         return self.cleaned_data
     1617>>> f = StartEnd({'start': '2', 'end': '1'})
     1618>>> f.is_valid()
     1619False
     1620>>> f.errors.get('start')
     1621[u'start must be smaller than end']
     1622>>> f = StartEnd({'start': '2'})
     1623>>> f.is_valid()
     1624False
     1625>>> type(f.errors.get('start'))
     1626<type 'NoneType'>
     1627>>> f = StartEnd({'start': '1', 'end': '2'})
     1628>>> f.is_valid()
     1629True
    16061630"""
  • django/newforms/util.py

     
    2727    def as_text(self):
    2828        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()])
    2929
     30    def append(self, name, message):
     31        errorlist=self.get(name)
     32        if errorlist==None:
     33            errorlist=ErrorList()
     34            self[name]=errorlist
     35        errorlist.append(message)
     36           
    3037class ErrorList(list, StrAndUnicode):
    3138    """
    3239    A collection of errors that knows how to display itself in various formats.
  • docs/newforms.txt

     
    14601460      "field" (called ``__all__``, which you can access via the
    14611461      ``non_field_errors()`` method if you need to.
    14621462
     1463
     1464      Instead of raising an ValidationError inside ``Form.clean()``,
     1465      you can add an error message with
     1466      ``self.errors.append(fieldname, message)``. This way the error message
     1467      will be displayed near the given field.
     1468
    14631469These methods are run in the order given above, one field at a time.  That is,
    14641470for each field in the form (in the order they are declared in the form
    14651471definition), the ``Field.clean()`` method (or it's override) is run, then
Back to Top