python - 无法在 shell 中验证 Django 用户

标签 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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295d4c5a5d4c44484045694e44484045074a4644" rel="noreferrer noopener nofollow">[email protected]</a>"
>>> password = "testpassword"
>>> user = get_user_model().objects.create_user("TestUser", email, password)

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

>>> get_user_model().objects.all()
<QuerySet [<MyUser: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5723322423323a363e3b17303a363e3b7934383a" rel="noreferrer noopener nofollow">[email protected]</a>>]>
>>> u = get_user_model().objects.first()
>>> u.username
'TestUser'
>>> u.email
'<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e793829493828a868e8ba7808a868e8bc984888a" rel="noreferrer noopener nofollow">[email protected]</a>'
>>> 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()

模型.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'
>>> 

最佳答案

您正在使用 is_active=False 创建用户。默认的 ModelBackend 会阻止非事件用户进行身份验证。

如果您希望允许非事件用户进行身份验证,您可以启用 AllowAllUsersModelBackend 后端。或者,如果您只是尝试在 shell 中测试身份验证,请先设置user.is_active = True

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

请参阅 authorization for inactive users 上的文档了解更多信息。

关于python - 无法在 shell 中验证 Django 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46913200/

相关文章:

python - sys.argv 可以处理可选参数吗?

django - 在 Django+South 中添加一个非空的外键字段

django - 设置django-allauth 404错误?

python - PySerial:如何理解从串口读取时发生超时?

python - 如何在 python 中将字节作为输入而不进行任何操作?

Django 模型表单 "unique=True"

python - manage.py createsuperuser 不适用于自定义用户模型

python - django 的 ALLOWED_HOSTS 抛出错误 500?

Python - 包和设置文件

python - docker中的ngrok无法连接到Django开发服务器