When checking multiple Forms with is_valid, first try assigning them to variables.

Overview

For example, when you want to check if multiple Forms are entered properly in django, why not write it in the following simple form?


foo_form = HogeForm(request.POST, prefix="FooForm")
bar_form = FooForm(request.POST, prefix="BarForm")

if foo_form.is_valid() and bar_form.is_valid():
    #Appropriate processing
    pass
else:
    pass

Even with this, it is possible to retrieve the error if either form is moss for the time being, but the problem is if both forms are moss. At that time, do not assume that is_valid () of bar_form is executed.

why?

The simple story is that in the case of Python, in the case of the judgment formula connected by and, the evaluation is not executed after the first False. Let's write a simple code.

# -*- coding: utf-8 -*-


def return_True():
    print "Call: return_True"
    return True


def return_False():
    print "Call: return_False"
    return False


if return_True() and return_True() and return_False() and return_True():
    print "All True ?"
else:
    print "Not all True."

In this case, "Call: return_True" was displayed twice and "Call: return_False" was displayed only once. The execution of the last function has been skipped. This is because * and once False appears, the whole becomes False *. So, in order to omit resources, it will be like "Then, that's False" without checking other things. (Similarly, once true appears for or, the subsequent judgment is skipped.)

what will you do?

The simplest is to prepare a variable. For example?

# -*- coding: utf-8 -*-


def return_True():
    print "Call: return_True"
    return True


def return_False():
    print "Call: return_False"
    return False

one_return_True = return_True()
two_return_True = return_True()
three_return_False = return_False()
forth_return_True = return_True()

if (one_return_True and
        two_return_True and
        three_return_False and
        forth_return_True):
    print "All True ?"
else:
    print "Not all True."

This way, "return_True" will also be displayed three times.

Summary

In the first place, when the behavior is entwined with other methods on the premise of calling some method, or when using a method that returns a Boolean after processing with a method with if etc., like the above, The method that you think "should be running!" Is not running.

Recommended Posts

When checking multiple Forms with is_valid, first try assigning them to variables.
First YDK to try with Cisco IOS-XE
[First API] Try to get Qiita articles with Python
When I try to push with heroku, it doesn't work