how to pass a context variable from a variable inside of an if statement?

Question:

Inside of an if statement I’ve check_order that I need to have as a context variable for my template, I’m getting this traceback: local variable 'check_order' referenced before assignment. How do I have it as a context variable without having to repeat the code to have it outside of the if statement?

View

if request.method == "POST":
    if request.user.is_authenticated:
        customer = request.user.customer
        check_order = OrderItem.objects.filter(order__customer=customer)
        if check_order:
            if form.is_valid():
                #does logic
        else:
            messages.error(request, f"Failed")
    else:
        return redirect()

context = {"check_order": check_order}
Asked By: betty_

||

Answers:

This is happening because of variable scoping. check_order is declared within a branch of an if statement, but referenced outside of that branch – it’s not in scope, so Python is throwing an error letting you know that you’re using it before it is defined.

You can read more about Python scope here: https://realpython.com/python-scope-legb-rule/.

The following code will address your issue:

# Declare check_order with no value but in the same scope it is referenced
check_order = None

if request.method == "POST":
    if request.user.is_authenticated:
        customer = request.user.customer
        check_order = OrderItem.objects.filter(order__customer=customer)
        if check_order:
            if form.is_valid():
                #does logic
        else:
            messages.error(request, f"Failed")
    else:
        return redirect()

context = {"check_order": check_order}
Answered By: Zailef
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.