Search code examples
djangosession-variables

Incresing session variable value in django


I'm creating a token everytime user access webpage, And the Token End have a 3 digit counter,Each time user refresh the page the counter should increment ,But i Can't Figure it out.How to initialize the session variable for the first time and increment in the rest of session.

Views.py

    def home(request):
         request.session['num'] = 1
    
         request.session['num'] += 1

         res = ''.join(random.choices(string.ascii_uppercase + string.digits,k=10 ))
    

         res1 = ''.join(res+str(request.session['num'] ).zfill(3))

    
         request.session['tk'] = res1
         return render(request,'home.html',{'res':res1})

home.html

    {% block content %}
    <h1>Token Generation </h1>
    <form action="{% url 'send' %}" method="POST">
        {% csrf_token %}
        
        <div class="form-group">
            <label for="exampleInputPassword1">Token : </label>
            <label for="exampleInputPassword1" name="res12">{{res}}</label>
        </div>
       
        <button type="submit" class="btn btn-primary">Send</button>
    </form>

{% endblock content %}

Can anybody Help me.


Solution

  • Check if the num is in request.session or not before you increase the value of it

    def home(request):
       ...
       num = request.session.get('num')
       if num is None:
           request.session['num'] = 1
       else:
           request.session['num'] +=1
       
       return render(request, 'home.html', {'num': num})
            
    

    also you can use try...except to achieve the same goal and it's more pythonic

    def home(request):
        try:
            request.session['num'] +=1
        except KeyError:
            request.session['num'] = 1
        return render(request, 'home.html', {'num': request.session['num']})