2

I've run into this issue before and solved it, but this just popped up totally randomly (or so it seems). I've just come back to my Django project after a little while away from it...when logging in I forgot my web username and it gave me the appropriate error message Sorry, that's not a valid username or password. So to solve this I created a new superuser (since I had also forgot my admin username) so I could check what my web username was. I did that successfully, but now when I try to login I get the CSRF error (whether the username or password is correct or not). I have no idea how this happened since it was validating properly 10 seconds ago and I didn't change a single line of code.

{% extends "base.html" %}

{% block content %}

    <title>{% block title %} | Login{% endblock %}</title>

    <h2>Login</h2>

    {% if form.errors %}
        <p class="error">Sorry, thats not a valid username or password</p>
    {% endif %}

    <form action="/accounts/auth/" method="POST">{% csrf_token %}
        <label for="username">Username: </label>
        <br>
        <input type="text" name="username" value="" id="username">
        <br><br>
        <label for="password">Password: </label>
        <br>
        <input type="password" name="password" value="" id="password">
        <br><br>
        <input type="submit" value="Login">
    </form>

{% endblock content %} 
123
  • 8,733
  • 14
  • 57
  • 99
  • Ok...after trying 3 or 4 times it works now...I didn't change anything...strangest bug I've ever seen... – 123 Nov 23 '15 at 23:40
  • is not a good practice but if you have problems with the CSRF TOKEN, use the decorator @csrf_exempt in your view. **I repeat is not a good practice.** – Joseleg Nov 23 '15 at 23:51

1 Answers1

9

For security purposes, the CSRF token is changed ('rotated') when you log in. If you open a page in Tab A, then log in on Tab B, then attempt to submit the form in Tab A, you will get a CSRF error, because the CSRF token in Tab A is out of date.

When you refresh Tab A, a new CSRF token is loaded, and the errors will stop.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I want to add that if you want to handle the error in an user friendly way [this](https://code.djangoproject.com/ticket/21704) might be helpful – Duilio Jan 05 '21 at 15:10
  • It's old but 8 years later still the same issue, this is poor design. If the tokens invalid and debug disabled it should be handled some other way the keep displaying server error out of the box without customizing anything. Its odd that any other service you try to use (emails, webapps) just ask you to login again – Elcast Feb 06 '23 at 17:28