Ticket #5335: append-r9698.diff

File append-r9698.diff, 4.4 KB (added by Ivan Giuliani, 16 years ago)

updated patch, tests and documentation

  • django/forms/util.py

     
    2929    def as_text(self):
    3030        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()])
    3131
     32    def __getitem__(self, field):
     33        if not self.has_key(field):
     34            super(ErrorDict, self).__setitem__(field, [])
     35        return super(ErrorDict, self).__getitem__(field)
     36
    3237class ErrorList(list, StrAndUnicode):
    3338    """
    3439    A collection of errors that knows how to display itself in various formats.
  • tests/regressiontests/forms/forms.py

     
    707707>>> f.cleaned_data['password2']
    708708u'foo'
    709709
     710Test that you can append errors to a field in the clean() method of a Form. This way you
     711can place the error message using a shorter syntax (i.e.: self._errors['fieldname'].append(u'error message'))
     712>>> class AppendErrors(Form):
     713...    field1 = IntegerField()
     714...    field2 = IntegerField()
     715...    def clean(self):
     716...        if self.cleaned_data['field1'] <= self.cleaned_data['field2']:
     717...            self._errors['field1'].append(u"Field1 can't be greater than Field2!")
     718...        return self.cleaned_data
     719>>> f = AppendErrors()
     720>>> f.errors
     721{}
     722>>> f.errors['field1']
     723[]
     724>>> f = AppendErrors({'field1': 5, 'field2': 10})
     725>>> f.errors
     726{'field1': [u"Field1 can't be greater than Field2!"]}
     727>>> f.errors['field1']
     728[u"Field1 can't be greater than Field2!"]
     729>>> f.errors['field2']
     730[]
     731
     732
    710733# Dynamic construction ########################################################
    711734
    712735It's possible to construct a Form dynamically by adding to the self.fields
  • docs/ref/forms/validation.txt

     
    107107display itself in different ways. So you can treat ``_errors`` as a dictionary
    108108mapping field names to lists.
    109109
    110 If you want to add a new error to a particular field, you should check whether
    111 the key already exists in ``self._errors`` or not. If not, create a new entry
    112 for the given key, holding an empty ``ErrorList`` instance. In either case,
    113 you can then append your error message to the list for the field name in
    114 question and it will be displayed when the form is displayed.
     110If you want to add a new error to a particular field, you can append your error
     111message to the list for the field name in question by using ``append()``.
     112Django will check if the key already exists, otherwise it will create an empty
     113``ErrorList`` instance. Then the error message will be displayed when the form
     114is displayed.
    115115
    116116There is an example of modifying ``self._errors`` in the following section.
    117117
     
    272272            subject = cleaned_data.get("subject")
    273273
    274274            if cc_myself and subject and "help" not in subject:
    275                 # We know these are not in self._errors now (see discussion
    276                 # below).
    277275                msg = u"Must put 'help' in subject when cc'ing yourself."
    278                 self._errors["cc_myself"] = ErrorList([msg])
    279                 self._errors["subject"] = ErrorList([msg])
     276                self._errors["cc_myself"].append(msg)
     277                self._errors["subject"].append(msg)
    280278
    281279                # These fields are no longer valid. Remove them from the
    282280                # cleaned data.
     
    288286
    289287As you can see, this approach requires a bit more effort, not withstanding the
    290288extra design effort to create a sensible form display. The details are worth
    291 noting, however. Firstly, earlier we mentioned that you might need to check if
    292 the field name keys already exist in the ``_errors`` dictionary. In this case,
    293 since we know the fields exist in ``self.cleaned_data``, they must have been
    294 valid when cleaned as individual fields, so there will be no corresponding
    295 entries in ``_errors``.
     289noting, however. Firstly, we mentioned that in order to add errors to the
     290fields, you just need to ``append()`` your error message in the ``_errors``
     291dictionary.
    296292
    297293Secondly, once we have decided that the combined data in the two fields we are
    298294considering aren't valid, we must remember to remove them from the
Back to Top