user7795844
user7795844

Reputation:

DJango form.is_valid() function only clean the first form in an if statement

I notice that forms.is_valid only clean form for the first form in an if statement.

Example code :

if not user_detail_form.is_valid() and not user_location_form.is_valid():
       return redirect('account:profile')

Accessing cleaned data of user_detail_form works but when accessing cleaned data of user_location_form, it throws an error stating that cleaned_data does not exists.

My question is

What causes this? and is there a workaround for this?

Upvotes: 1

Views: 181

Answers (1)

user707650
user707650

Reputation:

Evaluate your forms before the if-statement, to avoid missing evaluation due to and short-circuiting:

detailvalid = user_detail_form.is_valid()
locationvalid = user_location_form.is_valid()
if not detailvalid and not locationvalid:
   return redirect('account:profile')

More generally, in

if 1 == 2 and 3 == 3:

the second part is never evaluated, because the first part fails.

With or, it's the other way around:

if 1 == 1 or 2 == 3:

now, the first part succeeds, and the second part is (again) never evaluated.

More importantly, in both cases, if that second part involves a function call (e.g. is_valid()), that function is never called.

More info at this SO question, in particular the second answer.

Upvotes: 1

Related Questions