Created
April 15, 2015 15:35
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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