简体   繁体   中英

Testing a django session variable in a django view and return

I am trying to perform a selective operation based on the sessions variables set.

This is how I try-

   try:
        if request.session.get('firstoption', False):
            # perform operation for first option
            return redirect(reverse('first_option_view'))
    except:
        try:
            if request.session.get('secondoption', False):
                # perform operation for second option
                return redirect(reverse('second_option_view'))
        except:
            return HttpResponse("WTF!")

The execution hits the first if request.session.get('firstoption', False): it returns none, in the case of second case, instead of going to except, it returns the following error - views.viewname didn't return an HttpResponse object .

What am I doing wrong?

The get is returning None or False, but not an exception; your if is thus not executing the yes branch, but this is not an exception. You are simply then skipping the rest of the code and exiting the function without returning anything. You should have an else.

If you are not expecting any exceptions then you will not need a try except block.

if request.session.get('firstoption', False):
    # perform operation for first option
    return redirect(reverse('first_option_view'))

if request.session.get('secondoption', False):
    # perform operation for second option
    return redirect(reverse('second_option_view'))

else:
    return HttpResponse("WTF!")

It looks like you should be using a form for this. That way you can build in error checking for invalid inputs and many other benefits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM