Handle variable that could be None

2020-07-30 02:54发布

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

标签: python django
1条回答
疯言疯语
2楼-- · 2020-07-30 03:09

In the general case of checking if something is None.. just check it?

if x is not None and x.is_valid():
   ...

In Python, or and and both short circuit, meaning that in the expression x and y, y is not evaluated if x is false (since the expression is false no matter what y is).

查看更多
登录 后发表回答