~ / blog / development / raise-form-validation-error-from-form_valid-method
django 2022-08-22·1 min read

Raise Form Validation Error from form_valid() Method

In case if you need to make some validation steps directly in the view’s def form_valid() method and raise an ValidationError here an example

Non field error example

python
def form_valid(self, form):
    # validation logic
    if something_wrong:
        form.add_error(None, 'Something wrong with given data')
        return super().form_invalid(form)
    super().form_valid(form)

Field error

python
def form_valid(self, form):
    # validation logic
    if something_wrong:
        form.add_error('field_name', 'Something wrong with given data')
        return super().form_invalid(form)
    super().form_valid(form)