我有urls.py:Django 1.4 CSRF如何工作?
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(
r'^login/$',
'django.contrib.auth.views.login',
{'template_name': 'loyalty/login.html'},
name='login'
),
url(
r'^logout/$',
'django.contrib.auth.views.logout',
{'next_page': '/', },
name='logout'),
)
,並有模板的login.html *:
{% extends "loyalty/auth.html" %}
{% load i18n %}
{% block auth_form %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="" method="post" id="login-form">{% csrf_token %}
{% if form.username.errors %}{{ form.username.errors }}{% endif %}
{{ form.username }}
{% if form.password.errors %}{{ form.password.errors }}{% endif %}
{{ form.password }}
<input type="hidden" name="this_is_the_login_form" value="1" />
<input type="hidden" name="next" value="{{ next }}" />
<button type="submit" name="submit">{% trans 'Log in' %}</button>
</form>
{% endblock %}
和我有settings.py:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
但是這給了我這個錯誤:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF cookie not set.
在管理界面,我有同樣的問題。
我能做些什麼來解決這個問題?
我使用標準的Django應用程序,它在urls.py中看到:django.contrib.auth 在管理界面我有同樣的問題。 – lmasikl
@lmasikl:更新了答案看看 –
不適合我( – lmasikl