gpt4 book ai didi

django - 在 Django 1.5 中验证自定义用户

转载 作者:行者123 更新时间:2023-12-03 09:27:52 26 4
gpt4 key购买 nike

我在 Django 1.5 项目中有一个自定义用户,它使用 email 字段作为用户名:

class MyUser(AbstractUser):
my_custom_field = models.CharField(max_length=20, blank=True, null=True)

USERNAME_FIELD = 'email'

MyUser._meta.get_field_by_name('email')[0]._unique = True
MyUser.REQUIRED_FIELDS.remove('email')

如果我尝试像这样验证该用户:

auth_user = authenticate(username=email, password=password)
login(request, auth_user)

我明白了:

Traceback:
File "/Users/user/dev/proj/app/core/views.py" in post
39. login(request, auth_user)
File "/Users/user/.virtualenvs/proj/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
92. request.session[BACKEND_SESSION_KEY] = user.backend
File "/Users/user/.virtualenvs/proj/lib/python2.7/site-packages/django/utils/functional.py" in inner
203. return func(self._wrapped, *args)

Exception Type: AttributeError at /signup
Exception Value: 'AnonymousUser' object has no attribute 'backend'

我应该如何验证自定义用户?

最佳答案

我的自定义模型未在其显然需要的自定义管理器中实现 create_user()

这是完整的工作代码:

from django.contrib.auth.models import AbstractUser, BaseUserManager

class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')

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

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

def create_superuser(self, email, password):
user = self.create_user(email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user


class MyUser(AbstractUser):
some_custom_field = models.CharField(max_length=20, blank=True, null=True)

objects = MyUserManager()

USERNAME_FIELD = 'email'

MyUser._meta.get_field_by_name('email')[0]._unique = True
MyUser.REQUIRED_FIELDS.remove('email')

Django 1.5“自定义用户”实现是令人厌恶的。

关于django - 在 Django 1.5 中验证自定义用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16689056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com