Reputation: 1798
I have a login form like so:
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 %}
A login complete page like so:
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 %}
Login view:
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)
However the user does not get logged in. Username and password are correct (I tried with invalid combinations and I stay on the login page in that case and it displays an error) and I am using the correct login() method (auth.login and not my login() by accident).
Edit: My login() method is being called, it also shows me the login complete page correctly, but the
{% if user.is_authenticated %}
<p>foo</p>
{% endif %}
Edit2: Changing {% if user.is_authenticated %} to
{% if request.user.is_authenticated %}
does not work either.
What am I doing wrong?
Upvotes: 0
Views: 218
Reputation: 309099
Use render
instead of render_to_response
. The render_to_response
method is obsolete.
If you use render
, you don't need to do anything in the view to handle the csrf token, and you will be able to access any variables set by context processors like request
and 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)
You also need to update any other views that use render_to_response
, like login complete.
Upvotes: 2