Django测试客户端登录后返回匿名用户 [英] Django test client returns an anonymous user after login

查看:50
本文介绍了Django测试客户端登录后返回匿名用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用以下代码在Django中实现了用户登录;

I have implemented user login in Django using the following code;

在我的urls.py;

In my urls.py;

.
.
.
    url(r'^login/', UserLogin.as_view(), name='userlogin'),
.
.

在我的views.py;

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})
.
.
.

而我的auth/login.html是;

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()

我遇到以下失败;

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

推荐答案

该登录不会成功,因为Django希望密码为哈希值,但您已将其保存为纯文本格式.改为执行此操作:

That login won't succeed because Django expects the password to be a hash but you have saved it in plain text. Do this instead:

user = User.objects.create_user(username=username, password=password)

修改

您的问题很简单,尽管您的UserLogin视图具有名称,但实际上从未登录过该用户.AuthenticationForm执行其名称所隐含的内容,即进行身份验证,但是对此却不做任何事情经过身份验证的用户可以登录.

Your problem is quite simply that your UserLogin view, despite the name, never actually logs the user in. The AuthenticationForm does what its name implies, ie authenticates, but then does not do anything with that authenticated user to log them in.

至少,您需要在视图中的某个地方调用 login();但是似乎没有充分的理由让您在这里使用自己的自定义视图,而不是使用内置的 django.contrib.auth.views.login 视图.

At the very least, you would need to call login() somewhere in your view; but there doesn't seem to be a good reason for you to be using your own custom view here rather than the built-in django.contrib.auth.views.login view.

这篇关于Django测试客户端登录后返回匿名用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆