我有一个登录表单,可以将用户登录到管理站点。它在开发中工作正常,并且大多数在生产中工作正常,但有时它会给出403 CSRF验证失败错误。请注意,这种情况发生在之前能够登录的用户身上,因此我无法想象它的浏览器存在问题。
看起来jenniwren在this comment中有类似的问题。他们从来没有问过这个问题,其他评论者也不知道为什么会这样。
以下是我所拥有的:
urls.py
urlpatterns += patterns('django.contrib.auth.views',
url(r'^logout$', 'logout', {'next_page': 'mysite_login'}, name='mysite_logout'),
url(r'^login$', 'login', name='mysite_login'),
url('^', include('django.contrib.auth.urls')),
)
主要/注册/ login.html的
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
{% if form.errors and not form.non_field_errors %}
<p class="errornote">Please correct the error(s) below.</p>
{% endif %}
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
<p class="errornote">
{{ error }}
</p>
{% endfor %}
{% endif %}
<form action="{{ app_path }}" method="post" id="login-form">
{% csrf_token %}
<div class="form-row">
{% if form.errors %}
{ form.username.errors }}
{% endif %}
{{ form.username.label_tag }}
{{ form.username }}
</div>
<div class="form-row">
{% if form.errors %}
{{ form.password.errors }}
{% endif %}
{{ form.password.label_tag }}
{{ form.password }}
</div>
<input type="hidden" name="next" value="{{ next }}" />
<div class="submit-row">
<input type="submit" value="Log in" />
</div>
<div class="password-reset-link">
<a href="{% url 'password_reset' %}">Forgot your password?</a>
</div>
</form>
{% endblock content %}
settings.py
INSTALLED_APPS = (
'filebrowser',
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'psycopg2',
'main',
'mysite'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware'
)
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
CSRF_COOKIE_HTTPONLY = True
答案 0 :(得分:0)
如果出现此问题:
如果您的CSRF_FAILURE_VIEW
显示了您的网站模板,您可以让用户知道他们已经登录,并且无需刷新页面。
答案 1 :(得分:0)
我认为answer会为您提供帮助,您也可以使用@csrf_exempt
批注
在您的函数(视图)上这样:
@csrf_exempt
def foo():
return 'bar'
有关此主题的django文档:https://docs.djangoproject.com/en/3.0/ref/csrf/
答案 2 :(得分:0)
这是我收到的一条消息,即Debug = True:
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.