Django Test Client不会创建用户对象,但会创建匿名用户对象

时间:2015-04-06 17:42:23

标签: django python-2.7

我已经为我的项目实现了用户注册,我确实能够从Django shell客户端找到使用User.objects.get()创建的对象。

但是在运行测试时,似乎创建了一个AnonymousUser对象而不是User对象。

我有以下代码;

forms.py;

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserCreateForm(UserCreationForm):
    """
    Extends Django's UserCreationForm
    """
    email_exists_message = "A user with that email id already exists."
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField()

    class Meta:
        model = User
        fields = ("first_name", "last_name", "username", "email", "password1", "password2")

    def clean_email(self):
        email = self.cleaned_data["email"]
        try: 
            User._default_manager.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(
            self.email_exists_message,
            code='duplicate_email',
        )

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]
        if commit:
            user.save()
        return user

urls.py;

.
.
.
from stationrunner.forms import UserCreateForm
.
.

urlpatterns = patterns('',
    url('^registration/', 
        CreateView.as_view(template_name='auth/register.html',
                       form_class=UserCreateForm,
                       success_url='/stations/create'
        ),
        name='userregistration'
    ),
    .
    .
    .
)

最后是我的tests.py;

from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

class TestUserSignUp(TestCase):
    .
    .
    .
    def test_submission_form_creates_user_object(self):
    """
    Tests if submission of the form on page for creation of a 
    user creates a user object and its attributes take the 
    expected values
    """
    first_name = "somename"
    last_name = "somename"
    email = "someemail@someservice.com"
    username = "someusername"
    password = "somepassword"
    response = self.client.post(reverse("userregistration"),
                                {"first_name": first_name,
                                 "last_name": last_name,
                                 "email": email,
                                 "username": username,
                                 "password": password},
                                follow=True)
    assert "user" in response.context
    user = response.context["user"]
    assert user.first_name == first_name
    assert user.last_name == last_name
    assert user.email == email
    assert user.username == username
    assert user.password == user.set_password(password)

如上所述,用户对象确实被保存到db中,我还使用django shell中的userobject.is_authenticated()进一步确保它

但是当我运行测试时,我得到以下失败

>       assert user.first_name == first_name

stationrunner/tests.py:145: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _      _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser     object at 0x7f815ac211d0>>, args = ('first_name',)

    def inner(self, *args):
        if self._wrapped is empty:
            self._setup()
>       return func(self._wrapped, *args)
E       AttributeError: 'AnonymousUser' object has no attribute 'first_name'

我是Python / Django的新手,我非常期待有人向我解释这里发生了什么

阿夫扎尔

更新

我导入了身份验证并登录到我的forms.py并将save()方法更改为;

def save(self, commit=True):
    user = super(UserCreateForm, self).save(commit=False)
    user.email = self.cleaned_data["email"]
    user.first_name = self.cleaned_data["first_name"]
    user.last_name = self.cleaned_data["last_name"]
    if commit:
        user.save()
        authenticate(username=user.username, password=user.password)
        log_user_in(user)
    return user

并将预期的log_user_in()方法添加为;

def log_user_in(self, user):
    login(self.request, user)

我试图将用户登录,因此我希望我的response.context不包含匿名用户对象,而是包含用户对象本身。

但是代码似乎不起作用。我仍然得到同样的错误。如上所述,我是新手,所以请原谅,如果有任何愚蠢。

1 个答案:

答案 0 :(得分:1)

您正在创建新用户,但您没有以该用户身份进行身份验证。因此,您从response.context读取的用户是AnonymousUser。

如果您确实想在创建时登录用户,最好的方法是创建自己的表单视图。

否则,您必须更改测试以从数据库中读取新创建的用户。