我正在尝试实现一个用户永远不会离开首页的登录系统。到目前为止,我有以下内容:
表格:
<form action="" method="post">
{% csrf_token %}
<input type="text" name="username" value="" id="username">
<input type="password" name="password" value="" id="password">
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next|escape }}" />
</form>
观点:
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('index.html',{'state':state, 'username': username})
当我提交包含已知用户的表单时,我收到错误:
CSRF令牌丢失或不正确。
我做错了什么?我在表格中有令牌。
答案 0 :(得分:1)
您发布的示例代码使用了render_to_response而没有context_instance。
使用django.contrib.shortcuts.render代替render_to_response,全部您的观看次数。否则,{%csrf_token%}将为空。