I have implemented user login in Django using the following code;
In my urls.py;
.
.
.
url(r'^login/', UserLogin.as_view(), name='userlogin'),
.
.
In my views.py;
.
.
from django.contrib.auth.forms import AuthenticationForm
.
.
.
class UserLogin(FormView):
form_class = AuthenticationForm
template_name = "auth/login.html"
def get_success_url(self):
return reverse('userhome', kwargs={'pk': self.request.user.id})
.
.
.
and my auth/login.html is;
{% block head %}
<title>Open Radio | Login</title>
{% endblock %}
{% block body %}
<header>
<h1>Open Radio</h1>
<h2>Login Page</h2>
</header>
<section>
{% if form.errors %}
<p>Your username and password didn't match, please try again. </p>
{% endif %}
<form method="post" action=".">
{% csrf_token %}
<p>
<label for="id_username">Username:</label>
{{ form.username }}
</p>
<p>
<label for="id_password">Password:</label>
{{ form.password }}
</p>
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
<input type="submit" value="login" />
</form>
</section>
{% endblock %}
It works and does take me to the user's home page that I have defined.
But when I run the following test;
class TestLoginPage(TestCase):
.
.
.
def test_page_logs_in(self):
"""
Tests if the login page actually logs a user in
"""
username = "someusername"
password = "somepassword"
user = User(username=username,
password=password)
user.save()
response = self.client.post(reverse("userlogin"),
{"username":username,
"password":password},
follow=True)
assert response.context["user"].is_authenticated()
I get the following failure;
self = <stationrunner.tests.TestLoginPage testMethod=test_page_logs_in>
def test_page_logs_in(self):
"""
Tests if the login page actually logs a user in
"""
username = "someusername"
password = "somepassword"
user = User(username=username,
password=password)
user.save()
response = self.client.post(reverse("userlogin"),
{"username":username,
"password":password},
follow=True)
> assert response.context["user"].is_authenticated()
E AssertionError: assert <bound method AnonymousUser.is_authenticated of <django.contrib.auth.models.AnonymousUser object at 0x7f54b5433a50>>()
E + where <bound method AnonymousUser.is_authenticated of <django.contrib.auth.models.AnonymousUser object at 0x7f54b5433a50>> = <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f54b5433a50>>.is_authenticated
Could anyone please explain why is this happening