Login

Add ValidationError to a field instead of __all__ during Form.clean()

Author:
guettli
Posted:
October 13, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

If you need two values for validation, you can't use clean_value_a() since it is undefined if value_a or value_b gets cleaned first.

This little helper lets you add ValidationErrors to fields instead of _all_.

Related Ticket 5335.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# Related http://code.djangoproject.com/ticket/5335
def errors_append(form, field_name, message):
    u'''
    Add an ValidationError to a field (instead of __all__) during Form.clean():

    class MyForm(forms.Form):
        def clean(self):
            value_a=self.cleaned_data['value_a']
            value_b=self.cleaned_data['value_b']
            if value_a==... and value_b==...:
                formutils.errors_append(self, 'value_a', u'Value A must be ... if value B is ...')
            return self.cleaned_data
    '''
    assert form.fields.has_key(field_name), field_name
    error_list=form.errors.get(field_name)
    if error_list is None:
        error_list=forms.util.ErrorList()
        form.errors[field_name]=error_list
    error_list.append(message)
    

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.