CSRF验证失败 - Django
我不知道怎么解决这个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
在你的视图中,返回一个 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))
3
你需要把这个令牌(token)添加到模板的上下文中,试试下面的做法,并且去看看评论里提到的文档或教程。
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)