Skip to content
Advertisement

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

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)

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement