4

我正在使用 django 设计一个基本的登录和注销页面。所以下面是我的代码

设置.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',
    .......
    ....... 
)

网址.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

视图.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>

登录.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 %}

Login所以上面是我的完整代码,当我们点击给出的链接时,它会显示一个登录表单base.html

登录显示并输入一些usernamepassword单击Login按钮后,显示了一个错误页面,指示csrf error已显示

google了很多,加{% csrf_token %}在form标签里面,也加django.core.context_processors.csrf在template context过程中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)不起作用

4

1 回答 1

6

您需要将 a 传递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 文档了解更多信息。

在您的情况下,您的login视图正在呈现login.html模板,但没有传递 csrf 令牌。当login.html模板回传到服务器(到/logged_in)时,logged_in视图会检查该 csrf 令牌。它不存在(因为您从未包含它)。所以它假设它收到了一个跨站点请求伪造。

阅读csrf 文档以更了解该过程。

于 2013-03-01T07:08:50.163 回答