我有一个像这样的登录表单:
login_form.html
{% extends "base.html" %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
<form action="/accounts/login/" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login" />
</form>
{% endblock %}
登录完整页面如下:
login_complete.html
{% extends "base.html" %}
{% block title %}You are logged in{% endblock %}
{% block content %}
<h2>Thank you for logging in</h2>
{% if user.is_authenticated %}
<p>foo</p>
{% endif %}
{% endblock %}
登录视图:
def login(request):
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
auth.login(request, form.get_user())
return HttpResponseRedirect("/accounts/login/complete")
else:
form = AuthenticationForm()
token = {}
token.update(csrf(request))
token["form"] = form
return render_to_response("registration/login_form.html", token)
然而,用户没有登录。用户名和密码是正确的(我尝试使用无效组合,在这种情况下我留在登录页面并显示错误)并且我使用正确的login()方法( auth.login而不是我的登录()意外)。
编辑:我正在调用我的login()方法,它还会正确显示登录完成页面,但是
{% if user.is_authenticated %}
<p>foo</p>
{% endif %}
EDIT2: 更改 {%if user.is_authenticated%} 到
{% if request.user.is_authenticated %}
也不起作用。
我做错了什么?
答案 0 :(得分:2)
使用render
代替render_to_response
。 render_to_response
方法已过时。
如果您使用render
,则无需在视图中执行任何操作以处理csrf令牌,并且您将能够访问由request
等上下文处理器设置的任何变量和user
。
def login(request):
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
auth.login(request, form.get_user())
return HttpResponseRedirect("/accounts/login/complete")
else:
form = AuthenticationForm()
context = {'form': form}
return render(request, "registration/login_form.html", form)
您还需要更新使用render_to_response
的任何其他视图,例如登录完成。