我目前正在尝试实现我自己的用户模型。因此我创建了一个新的应用程序“帐户”。但是每次我尝试创建新用户时,都会出现以下错误:
AttributeError:“AnonymousUser”对象没有属性“_meta”
帐户-models.py:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
#User Model Manager
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a User with the given username and password.
"""
if not username:
raise ValueError('Error: The User you want to create must have an username, try again')
user = self.model(
user=self.normalize_username(username),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, username, password):
"""
Creates and saves a staff user with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
#User fields
user = models.CharField(verbose_name='username',max_length=30,unique=True)
bio = models.TextField(max_length=5000, blank=True, null=True)
pubpgp = models.TextField(blank=True, null=True)
#Account typs
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that's built in.
USERNAME_FIELD = 'user'
REQUIRED_FIELDS = [] # Username & Password are required by default.
def get_full_name(self):
# The user is identified by their Username ;)
return self.user
def get_short_name(self):
# The user is identified by their Username address
return self.user
def __str__(self):
return self.user
def has_perm(self, perm, obj=None):
"""Does the user have a specific permission?"""
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"""Does the user have permissions to view the app `app_label`?"""
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"""Is the user a member of staff?"""
return self.staff
@property
def is_admin(self):
"""Is the user a admin member?"""
return self.admin
@property
def is_active(self):
"""Is the user active?"""
return self.active
objects = UserManager()
之后我跳回 settings.py 并将自定义用户模型添加到我的实际博客应用程序中:
AUTH_USER_MODEL = 'accounts.User'
我还添加了
INSTALLED_APPS = [
...
'accounts',
...
]
所有这些用户模型/django 的东西对我来说有点新,我不知道错误“AttributeError:'Manager' object has no attribute 'get_by_natural_key'”是什么意思。
感谢:D