Home > Software design >  how to pass a context variable from a variable inside of an if statement?
how to pass a context variable from a variable inside of an if statement?

Time:12-01

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}

CodePudding user response:

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}
  • Related