django csrf验证失败请求被中断
CSRF验证失败。 请求中止。 在Django上 (4)
我正在关注Django 1.3 Web Development。 和登录,我收到以下错误
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
这是我的settings.py包含APPS。 这本书是如何说的。
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'djangocricket.Cricket',
'djangocricket.cms'
)
这本书说,它应该包含,django.contrib.auth.views.login ..我包括它在
urlpatterns = patterns('',
# Examples:
url(r'^$', 'djangocricket.Cricket.views.index', name='default'),
url(r'^user/(\w+)/$', 'djangocricket.Cricket.views.user_home', name='user home'),
url(r'^login/$', 'django.contrib.auth.views.login'),
# url(r'^djangocricket/', include('djangocricket.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^news/', 'djangocricket.cms.views.index', name='index'),
#url(r'^news/(?P<slug>[^\.]+).html', 'djangocricket.cms.views.detail', name='get_single_news_item'),
url(r'^admin/', include(admin.site.urls)),
)
和我的注册/ login.html ...复制从书上粘贴。 它应该做的。
<html>
<head>
<title>Django Bookmarks - User Login</title>
</head>
<h1>User Login</h1>
{% if form.errors %}
<p>Your username and password didn't match.
Please try again.</p>
{% endif %}
<form method="post" action=".">
<p><label for="id_username">Username:</label>
{{ form.username }}</p>
<p><label for="id_password">Password:</label>
{{ form.password }}</p>
<input type="hidden" name="next" value="/" />
<input type="submit" value="login" />
</form>
</body>
</html>
我错过了什么?
只是想给这个主题的额外信息。 如果它发生在你身上,而且你确定这个令牌被注入到表单中,并且视图函数正确地处理了一切,但问题仍然存在。 确保没有JavaScript代码禁用输入字段。 发生在我身上,经过几个小时的调试,终于意识到这一点。
<input type="hidden" name="csrfmiddlewaretoken" value="pHK2CZzBB323BM2Nq7DE2sxnQoBG1jPl" disabled="">
嗨,只需在表单中使用{%csrf_token%}即可。 那么为什么我们要使用跨站请求伪造? 好吧,答案非常简单,只是在网页中添加了另一个安全层,任何恶意用户都无法使用错误的令牌来验证请求。
您需要将{% csrf_token %}
模板标记添加为您的Django模板中form
元素的子元素。
这样,模板将呈现一个隐藏的元素,其值设置为CSRF标记。 当Django服务器接收到表单请求时,Django将验证该令牌是否与表单中呈现的值匹配。 这对于确保POST请求(即数据更改请求)源自可信的客户端会话是必需的。
有关更多信息,请查看以下位置的Django文档: https : //docs.djangoproject.com/en/dev/ref/csrf/
以下是跨站请求伪造攻击的概述: https : //www.owasp.org/index.php/CSRF
我有同样的问题。 我在添加{%csrf_token%}时解决了这个问题。 最后我的代码是这样的:
<form id='formulario2' method='post' action='>
<h3>Enter:</h3>
{% csrf_token %}
<input id="id_mesaje" name="mesaje" type="email" placeholder="E-mail"/>
<input type='submit' name="boton2" value='Suscribete' style="display:inline-block;background-color: #80e174; "/>
</form>