0

I am a new to the Django framework.

I have created a simple arithmetic application using django.

As suggested in the django documentation, I wrote

{% csrf_token %}

in my template file.

But, the thing i notice is that, token value is not changing on post request.

It is showing same value every time with expiry of 364 days

So, let me know the settings to change CSRF Token Value in each post request.

Thanks in advance

My template code below

    <form action="{{ action }}" method="post">
        {% csrf_token %}
        <fieldset>
            <legend>{{ tag }}:</legend>
            Number 1: <input type="text" size="10" name="num1" value="{{ n1|default:0 }}"><br>
            <span> {{ operator }} </span><br>
            Number 2: <input type="text" size="10" name="num2" value="{{ n2|default:0 }}"><br>
            <span> = </span><br>
            Result&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: <input type="text" size="10" value="{{ res|default:0 }}" disabled>
            &nbsp; <span>{{ warning|default:'' }} </span><br><br>
            <input type="submit" size="10">
        </fieldset>
    </form>

    <a href="/app1">App1 Home</a>

My view code below

def add(request):
    warn = ''
    res, n1, n2 = (0, 0, 0)

    try:
        n1 = int(request.POST['num1'])
        n2 = int(request.POST['num2'])
        res = n1 + n2
    except (ValueError, TypeError):
        warn = 'Text data is not allowed.'

    params = {'operator': '+', 'action': 'add', 'tag': 'Addition' ,'n1': n1, 'n2': n2, 'res': res, 'warning': warn}
    return render(request, 'arithmatic_app1.html', params)
Teymour
  • 1,832
  • 1
  • 13
  • 34
  • CSRF in django are tied to the user login session([create by the session](https://stackoverflow.com/a/30539335/11225821)), when a user log out or their login session end(duration of a session can be changed) the token will change the next time user login, as for changing CSRF expire duration it's not recommend as stated by this [answer](https://stackoverflow.com/a/19186747/11225821) – Linh Nguyen Jan 09 '20 at 07:43
  • I found this answer useful regarding the RequestContext. https://stackoverflow.com/questions/5691647/django-csrf-requestcontext – tomgalpin Jan 09 '20 at 08:06

0 Answers0