1

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}
2
  • 3
    you can decarle check_order before your if statement otherwise check if the check_order query returns a queryset, if it returns none, thats your problem Commented Nov 30, 2022 at 11:12
  • Logical mistake. Your are passing 'check_order' context then declare that variable in same level of it. Commented Nov 30, 2022 at 11:50

1 Answer 1

3

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.