Raise Form Validation Error from form_valid() Method

Raise Form Validation Error from form_valid() Method

August 21, 2022
forms

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 #

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 #

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)

Comments