Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble with variable.
#1
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.
Reply
#2
(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")
Reply
#3
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.
Larz60+ write Jul-17-2023, 03:06 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use BBCode tags on future posts.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020