Although this is django related, it's really just a general, programming efficiency question.
I have a template that, depending on the scenario, will get and return either one or two forms. If it returns one form, the variable that holds the second form will be None.
I need to check if the forms are valid. Similar to an example I read online, I'm checking .is_valid() on both forms in the same if statement. But this unsurprisingly throws an error (NoneType object has no attribute is_valid) if the second form is None.
What is the best way to check that both forms are valid without incurring an error if the second form is None?
if request.method == 'POST':
form = form_dict[modelname][1](request.POST)
try:
form_two = form_dict[modelname][2](request.POST)
except:
form_two = None
if form.is_valid() and form_two.is_valid():
# Do some stuff and save the data from the form(s)
else:
try:
form = form_dict[modelname][1]()
form_two = form_dict[modelname][2]()
except:
form_two = None
In the general case of checking if something is
None
.. just check it?In Python,
or
andand
both short circuit, meaning that in the expressionx and y
,y
is not evaluated ifx
isfalse
(since the expression is false no matter whaty
is).