1

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?

  • both ```not user_detail_form.is_valid()``` and ```not user_location_form.is_valid()``` returns false. why did it skipped? –  Mar 10 '18 at 10:42
  • I don't think there is a way for my forms to be invalid because it's rendered by the template engine it self. –  Mar 10 '18 at 10:42
  • It didn't redirect either, if one of the conditions is true it would have redirected –  Mar 10 '18 at 10:44
  • I thought the code is like, "If both conditions is false redirect", not "if one condition is false, skipped it" –  Mar 10 '18 at 10:45
  • hmmm, thanks, this is a sign I need to learn more. –  Mar 10 '18 at 10:47
  • I always thought that the ```if and``` will execute a code if both is the same. apparently, it needs both to be true. –  Mar 10 '18 at 10:49
  • I've added some updates to my answer, including a link to a related question. Start there to study this behaviour. –  Mar 10 '18 at 10:54

1 Answers1

1

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.