Django – When button is clicked I want to change the dictionary content

Question:

On my html page I have a button, and a number being displayed. I want the number to increase by 1 every time the button is pressed. This is the code that I have so far, but for some it doesn’t work.

mypage.html

<form method='get' action='#'>
    <input type="submit" value="add" name="add"/>
</form>
<h1>{{ p }}</h1>

views.py

p = 1
def mypage(request):
    global p
    my_dictionary = {
        "p" : p,
    }
    if request.GET.get('add'):
        p = p+1
        my_dictionary = {
            "p" : p,
        }
    return render(request, "mypage.html", my_dictionary)
Asked By: PiccolMan

||

Answers:

On every request a new instance of the python script is run which would result in your global variable not being retained. You should store the count in a database and recall the value on every request. There are options other than a database but the basic idea of needing some sort of persistent storage still exists.

Alternatively, you can have the requester keep track of the count and provide the current count in the request. You would then add one to the value provided in the request. This would require some additional code on the front end to maintain the count, and even then, if the user closes the browser the count will be reset.

As dm03514 pointed out, you can can also use sessions like so:

if 'p' in request.session:    
   request.session['p'] = request.session['p'] + 1
else:
   request.session['p'] = 1
Answered By: Kevin

The p value needs to be kept track of across requests.

2 possibilities are

  • resend the data every request
  • store the data in a session and just make increment /decrement requests

Should the variable be shared between all users? Or just the current user?

Answered By: dm03514

It should work if there is a single instance of django running (although it is not the recommended approach like other’s have suggested).
It didn’t appear to work is because you used action='#', and the browser refused to resubmit the form when your URL already ends with #. Instead you can use the following template:

<form method='get' action='.'>
    <input type="submit" value="add" name="add"/>
</form>
<h1>{{ p }}</h1>
Answered By: Fabricator