CSRF令牌丢失或无效的Django [英] CSRF token missing or invalid Django
问题描述
我之前曾遇到过这个问题并已解决,但是这个问题是完全随机出现的(看起来如此)。我刚刚离开我的Django项目一会儿……当我登录时忘记了我的Web用户名,它给了我相应的错误消息很抱歉,该用户名无效或密码
。因此,为了解决这个问题,我创建了一个新的超级用户(因为我也忘记了管理员用户名),因此可以检查我的Web用户名是什么。我成功完成了此操作,但是现在尝试登录时,出现CSRF错误(用户名或密码是否正确)。我不知道这是怎么发生的,因为它已经在10秒钟前正确验证了,而且我没有更改一行代码。
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 %}
推荐答案
出于安全目的,登录时CSRF令牌会更改(旋转)。如果在选项卡A中打开页面,然后在选项卡B中登录,然后尝试在选项卡A中提交表单,则出现CSRF错误,因为标签A中的CSRF令牌已过期。
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.
刷新标签A时,将加载新的CSRF令牌,并且错误将停止
When you refresh Tab A, a new CSRF token is loaded, and the errors will stop.
这篇关于CSRF令牌丢失或无效的Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!