CSRF验证失败 - Django

时间:2013-03-08 22:42:57

标签: python django web

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

<!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})

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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))