Mirage
Mirage

Reputation: 31548

How can redirect to form invalid from the form_valid function in django

I am performing some more validation fater the main form has been validated. I am using class based views

def form_valid(self, request, *args, **kwargs):
    some custom logic
    if(false)
    Here i want to return to form invalid page with my custom message

I am processing the file in form_valid and thats got many steps which i need to check for more validation. so i don't want to move all that logic out to another function

Upvotes: 4

Views: 4037

Answers (1)

bradley.ayers
bradley.ayers

Reputation: 38382

You shouldn't be doing validation in form_valid. Do it in the form, either in Form.clean or Form.clean_FOO. Refer to the Django documentation on form validation.

If you insist on mutilating your code-base, then try the following:

def form_valid(self, request, *args, **kwargs):
    is_actually_valid = some_custom_logic()
    if not is_actually_valid:
        return self.form_invalid(request, *args, **kwargs)

Upvotes: 7

Related Questions