Skip to content

Instantly share code, notes, and snippets.

@cstrap
Created April 15, 2015 15:35
Show Gist options
  • Save cstrap/78b52b80ff0e40cefac1 to your computer and use it in GitHub Desktop.
Save cstrap/78b52b80ff0e40cefac1 to your computer and use it in GitHub Desktop.
Validate form django with a function that add the errors. Useful when one form data depends on other data field.
class MyForm(forms.Form):
# ...
def clean(self):
def set_field_error(field, message):
if field in self._errors:
self._errors[field].append(message)
else:
self._errors[field] = self.error_class([message])
if field in cleaned_data.keys():
del cleaned_data[field]
cleaned_data = super(MyForm, self).clean()
if not cleaned_data.get('form_key', None):
set_field_error('form_key', 'error message')
return cleaned_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment