2013-03-08 124 views
0

我不知道如何解决此CSRF故障。我已经包含了我一直在阅读的{%csrf_token%},但它仍然给我这个错误。下面是代码:CSRF验证失败 - Django

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
    <title>Log in</title> 
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 
    <style> 
     body{ 
     font-family:Arial,Helvetica,sans-serif; 
      font-size: 12px; 
     } 
    </style> 
    </head> 
    <body> 
     {{ state }} 
     <form action="/login/" method="post">{% csrf_token %} 
      {% if next %} 
      <input type="hidden" name="next" value="{{ next }}" /> 
      {% endif %} 
      username: 
      <input type="text" name="username" value="{{ username}}" /><br /> 
      password: 
      <input type="password" name="password" value="" /><br /> 

      <input type="submit" value="Log In" /> 
     </form> 
    </body> 
</html> 

我已经包括所有适当的功能,这个,但如果你需要看到更多的代码,让我知道......我想这是所有应用虽然...

编辑:views.py

from django.shortcuts import render_to_response 
from django.contrib.auth import * 

def login_user(request): 
    state = "Please log in below..." 
    username = password = '' 
    if request.POST: 
     username = request.POST.get('username') 
     password = request.POST.get('password') 

     user = authenticate(username=username, password=password) 
     if user is not None: 
      if user.is_active: 
       login(request, user) 
       state = "You're successfully logged in!" 
      else: 
       state = "Your account is not active, please contact the site admin." 
     else: 
      state = "Your username and/or password were incorrect." 

    return render_to_response('auth.html',{'state':state, 'username': username}) 
+0

是什么 “这个错误”?你能发布你所看到的错误的完整追溯吗?你能发布视图代码吗?它会帮助我们更好地诊断您的问题。 – sdolan 2013-03-08 22:45:01

+0

你是否只包含没有HTML标记的标记? – user2398029 2013-03-08 22:46:54

+0

^^^它应该被包括在内。 OP:你是否检查了HTML以查看'{%csrf_token%}'标签实际上是否生成了隐藏的输入元素?否则请复习点1.至3.这里:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ – Tobia 2013-03-08 22:47:51

回答

3

您需要将令牌添加到模板背景下,尝试这样的事情,并在文档/教程在评论你的问题链接到阅读起来。

from django.core.context_processors import csrf 

def login_user(request): 
    ...your code... 
    ctx = {'state':state, 'username': username} 
    ctx.update(csrf(request)) 
    return render_to_response('auth.html',ctx) 
+3

或者只使用'render'而不是'render_to_response'。 – wRAR 2013-03-09 01:18:09

0

在您看来,返回一个context_instance到模板如下

from django.template import RequestContext 
def login_user(request): 
    ... 
    return render_to_response('auth.html',{'state':state, 'username': 
    username},context_instance=RequestContext(request))