gpt4 book ai didi

django - CSRF 验证失败。请求中止。在 django 上

转载 作者:行者123 更新时间:2023-11-28 19:35:27 31 4
gpt4 key购买 nike

我正在关注 Django 1.3 Web 开发。对于登录,我收到以下错误

Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.

这是我的 settings.py 包含的应用程序。这正是书中所说的。

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)),
)

和我的 registration/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>

我错过了什么?

最佳答案

您需要在 Django 模板中添加 {% csrf_token %} 模板标记作为 form 元素的子元素。

这样,模板将呈现一个隐藏元素,其值设置为 CSRF token 。当 Django 服务器收到表单请求时,Django 将验证 token 是否与表单中呈现的值匹配。这是确保 POST 请求(即数据更改请求)源自真实客户端 session 所必需的。

有关更多信息,请查看 Django 文档: https://docs.djangoproject.com/en/dev/ref/csrf/

以下是跨站点请求伪造攻击的概述: https://www.owasp.org/index.php/CSRF

关于django - CSRF 验证失败。请求中止。在 django 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9692625/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com