Running: Python 3.9.9 and Django 4
I'm trying to put together a loop that waits for a users input and then appends that input to an existing dictionary. See code below:
def calculator(request):
loop_int = 1
numbers = [str(x) for x in range(0,10)]
i = "1"
current_nums = {'1':[],'2':[]}
if request.GET: #wait for request.GET to return True before starting while loop
while loop_int < 10:
r = request.GET #store request.GET object as r
if r: #this is here to stop the loop and wait for request.GET to return True
print(r)
if list(r.values())[0] in numbers:
digit = list(r.values())[0] #grab the value from request.GET
current_nums[i].append(digit) #append that value to the list at "1" in current_nums dictionary
print(f'digit = {digit}')
print(f'current_nums = {current_nums}')
loop_int = 1 #increment the loop_int
request.GET = None
return render(request, 'calculator/calculator.html')
The last print statement print(f'current_nums={current_nums}') displays the updated dictionary that I expect, but the appended digits don't persist through the next iteration of the loop. Code output below:
<QueryDict: {'1': ['1']}>
digit = 1
current_nums = {'1': ['1'], '2': []}
<QueryDict: {'2': ['2']}>
digit = 2
current_nums = {'1': ['2'], '2': []}
This file is a views.py file for a Django project. I'm having no issues (as far as I can tell) getting the information from the front end using request.GET.
One odd thing I discovered is that if I remove the statement request.GET = None at the end of the loop, which allows the loop to run uninterrupted with the same value for request.GET, then the program works as intended for the next 9 iterations and the dictionary updates persist. However, as soon as I try to set request.GET = None to pause the loop and wait for a legitimate user input, the dictionary updates stop persisting.
Am I making a simple scope error? Or is there a nuance to request.GET that I'm missing?
CodePudding user response:
Your problem is that you put current_nums in the view function, and every time a request comes in, it will be initialized.
You can put it outside the view function, like below, and it will save the data added with each request.
class Data:
loop_int = 1
current_nums = {'1':[],'2':[]}
numbers = [str(x) for x in range(0,10)]
def calculator(request):
i = "1"
if request.GET and Data.loop_int < 10: #wait for request.GET to return True before starting while loop
r = request.GET #store request.GET object as r
print(r)
if list(r.values())[0] in Data.numbers:
digit = list(r.values())[0] #grab the value from request.GET
Data.current_nums[i].append(digit) #append that value to the list at "1" in current_nums dictionary
print(f'digit = {digit}')
print(f'current_nums = {Data.current_nums}')
Data.loop_int = 1 #increment the loop_int
return render(request, 'calculator/calculator.html')
You can still use it for a single person to test locally. If it involves multiple concurrency, you need to lock it.
