Login

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

Author:
guettli
Posted:
October 13, 2008
Language:
Python
Version:
1.0
Tags:
errordict
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. Honeypot Field by SmileyChris 8 years ago
  2. Dynamically add css-classes to formfields by Lacour 3 years, 9 months ago
  3. DateTimeField with microseconds by tobias 6 years, 1 month ago
  4. MultiRangeField and MultiRangeFormField by bobtiki 10 months, 3 weeks ago
  5. CustomChoiceField, Selectable label field version of ModelChoiceField by mauro 7 years, 1 month ago

Comments

Please login first before commenting.