Python Forum

Full Version: Trouble with variable.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In a django project, i have the function below. I am trying to increment the toGoFor variable each time the button is pressed.

I have the following code.

def rtb(request):
    if request.method == 'POST':
        toGoFor += 1
        dict = { "toGoFor" : toGoFor}
        return render(request, 'rtb.html', dict)
    else: 
        toGoFor = 1
        dict = { "toGoFor" : toGoFor}
        return render(request, 'rtb.html', dict)
When it is run the first time it is called as a Get it works, but when the button is pressed I get the following error.
Quote:local variable 'toGoFor' referenced before assignment

Quite new to Django so any help be greatly appreciated.
(Jul-15-2023, 02:17 PM)angus1964 Wrote: [ -> ]In a django project, i have the function below. I am trying to increment the toGoFor variable each time the button is pressed.

I have the following code.

def rtb(request):
    if request.method == 'POST':
        toGoFor += 1
        dict = { "toGoFor" : toGoFor}
        return render(request, 'rtb.html', dict)
    else: 
        toGoFor = 1
        dict = { "toGoFor" : toGoFor}
        return render(request, 'rtb.html', dict)
When it is run the first time it is called as a Get it works, but when the button is pressed I get the following error.
Quote:local variable 'toGoFor' referenced before assignment

Quite new to Django so any help be greatly appreciated.

Dont use dict as variale this is internal python method like
x = dict(name = "John", age = 36, country = "Norway")
In your code, you're trying to increment the toGoFor variable without initializing it before the if statement. Therefore, when the code reaches the line toGoFor += 1, it doesn't have a value assigned to toGoFor yet.

def rtb(request):
    toGoFor = request.session.get('toGoFor', 0)  # Initialize toGoFor to 0 if not set in session
    
    if request.method == 'POST':
        toGoFor += 1
        request.session['toGoFor'] = toGoFor  # Store the updated value in the session
        context = {"toGoFor": toGoFor}
        return render(request, 'rtb.html', context)
    else: 
        context = {"toGoFor": toGoFor}
        return render(request, 'rtb.html', context)
In the above code i have used the Django session to store and retrieve the value of toGoFor. The session allows you to store data that persists across multiple requests.