无法在shell

时间:2017-10-24 14:29:07

标签: python django

由于某些原因,我无法在Django shell中验证新创建的用户,我真的不知道出了什么问题。一定是非常愚蠢的......

启动Django shell:

(venv) xxx:xxx xxx$ python ../manage.py shell
Python 3.6.0 (v3.6.0, ...) 
[GCC 4.2.1 (...) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

创建新用户:

>>> from django.contrib.auth import get_user_model
>>> email = "testemail@gmail.com"
>>> password = "testpassword"
>>> user = get_user_model().objects.create_user("TestUser", email, password)

新用户似乎已正确添加到数据库中:

>>> get_user_model().objects.all()
<QuerySet [<MyUser: testemail@gmail.com>]>
>>> u = get_user_model().objects.first()
>>> u.username
'TestUser'
>>> u.email
'testemail@gmail.com'
>>> u.password
'pbkdf2_sha256$36000$Onrvxuy09b6r$sCuz/2/bIbeg5j7cfO934kCIvzVdxqo1s1v6x6nwYLY='

但身份验证失败:

>>> from django.contrib.auth import authenticate
>>> user = authenticate(email = email, password = password)
>>> user.email
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'email'
>>>

我有自定义用户模型,因此使用get_user_model()

models.py:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class MyUserManager(BaseUserManager):
    def create_user(self, username, email, password=None):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email).lower(),
        )

        user.username = username
        user.is_active = False
        user.set_password(password)
        user.save(using=self._db)
        return user

        ...

class MyUser(AbstractBaseUser):
    email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
    is_active = models.BooleanField(default=False)
    username = models.CharField(max_length=50, default="Anonymous")
    is_guest = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    ...

非常感谢任何帮助!

以下内容也不起作用:

>>> user = authenticate(username="TestUser", password=password)
>>> user.email
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'email'
>>> 

1 个答案:

答案 0 :(得分:1)

You are creating the user with is_active=False. The default ModelBackend prevents inactive users from authenticating.

You could enable the AllowAllUsersModelBackend backend if you want your inactive user to be allowed to authenticate. Or, if you are just trying to test authenticate in the shell, then set user.is_active = True first.

user = get_user_model().objects.create_user("TestUser", email, password)
user.is_active = True
user.save()

See the docs on authorization for inactive users以获取更多信息。