我正在使用django设计一个基本的登录和注销页面。以下是我的代码
settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
...........
...........
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
"django.core.context_processors.csrf",
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
.......
.......
)
urls.py
from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', 'learn_django.views.home_page'),
url(r'^login/$', 'learn_django.views.login'),
url(r'^logged_in$', 'learn_django.views.logged_in'),
url(r'^logout/$', 'learn_django.views.logout'),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + urlpatterns
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def home_page(request):
return render_to_response("home_page.html")
def login(request):
return render_to_response("login.html")
def logged_in(request):
return render_to_response("logged_in.html",context_instance=RequestContext(request))
base.html文件
{% load staticfiles %}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="{% static 'css/home_remaining.css' %}" type="text/css">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<header>
<div class='header_div'>
<div class="logout"><p id='logout'><a href="/logout" >Logout</a></p><div>
<div class="login"><p id='login'> <a href="/login" >Login</a></p><div>
</div>
</header>
<div class="body_content">
{% block body %}{% endblock %}
</div>
</body>
</html>
的login.html
{% extends 'base.html' %}
{% block title %}Login Page{% endblock %}
{% block body %}
<div id='container'>
<form action="/logged_in" method="POST">
{% csrf_token %}
<label for="name">Username:</label><input type="name">
<label for="username">Password:</label><input type="password">
<div id="lower">
<input type="submit" value="Login">
</div>
</form>
</div>
{% endblock %}
以上是我的complet代码,当我们点击Login
中给出的base.html
链接时,会显示一个登录表单。
登录显示并输入了一些username
和password
并点击了Login
按钮后,显示的错误页面显示csrf error
搜索了很多并在表单标记中添加了{% csrf_token %}
,并在django.core.context_processors.csrf
settings.py
以下是错误消息,看起来像
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF cookie not set.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
所以当我从模板上下文进程中删除django.core.context_processors.csrf时,它的工作正常。但我也想使用csrf保护。
最后,实际上在上面的视图代码中出现了什么错误以及csrf错误页面出现的原因以及如何避免上述错误页面?
我是否需要在views.py
函数中添加任何代码?
任何人都可以在我上面的函数中添加基本的登录和注销功能代码,这样对于实际理解代码会更有帮助......
对于上述问题,我导入了csrf_exempt函数,如下所示
from django.views.decorators.csrf import csrf_exempt
并在logged_in
视图之前将其作为装饰器给出,当我点击登录按钮时它没有显示错误页面
但仍然想知道为什么下面提到的方法,比如从模板发送Requestcontext不起作用
答案 0 :(得分:6)
您需要将RequestContext
传递给render_to_response
函数。
def home_page(request):
return render_to_response("home_page.html", context_instance=RequestContext(request))
或者使用新的渲染函数,它处理为你传递RequestContext
。
def home_page(request):
return render(request, "home_page.html")
RequestContext将各种有用的东西添加到传递给模板的上下文字典中。这包括csrf令牌。有关详细信息,请查看RequestContext docs。
在您的情况下,您的login
视图正在呈现login.html
模板,但未传递csrf令牌。当login.html
模板回发到服务器(到/logged_in
)时,logged_in
视图会检查该csrf令牌。它不存在(因为你从未包括它)。所以它假定它收到了一个跨站请求伪造。
阅读csrf docs以更好地了解该过程。