我已使用以下代码在Django中实现了用户登录;
在我的urls.py中;
.
.
.
url(r'^login/', UserLogin.as_view(), name='userlogin'),
.
.
在我的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})
.
.
.
我的auth / login.html是;
{% 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 %}
它有效并且确实将我带到了我定义的用户主页。
但是当我运行以下测试时;
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()
我得到以下失败;
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
任何人都可以解释为什么会发生这种情况
答案 0 :(得分:3)
登录不会成功,因为Django希望密码是一个哈希,但你已经用纯文本保存了它。这样做:
user = User.objects.create_user(username=username, password=password)
修改强>
你的问题非常简单,你的UserLogin视图,尽管名称,从来没有实际登录用户.AuthenticationForm执行其名称暗示,即认证,但后来没有做任何事情经过身份验证的用户将其登录。
至少,您需要在视图中的某个地方拨打login()
;但是,在这里使用您自己的自定义视图而不是内置的django.contrib.auth.views.login
视图似乎不是一个很好的理由。