我正在使用 Django 1.5 构建一个 Web 应用程序。我正在使用带有自定义 UserManager 的自定义用户模型。
我遵循 Django 官方文档的说明和示例。
现在,当我尝试通过以下方式创建新用户时UserManager.create_user(...)
我收到 NoneType 错误:看来 UserManager 的属性模型的类型为 None。
我认为我在用户模型中正确设置了 UserManager (objects = UserManager()
)
我真的不知道我哪里错了。 Booth 我和我的编码伙伴都是 Django 新手。也许你可以帮助我们。
这是代码:
class UserManager(BaseUserManager):
"""
create a new user
@param username: the name for the new user
@param password: the password for the new user. if none is provided a random password is generated
@param person: the corresponding person object for this user
"""
def create_user(self, username, person, password=None):
if not username:
raise ValueError('User must have a valid username')
user = self.model(username=username, created=datetime.now(), must_change_password=True, deleted=False, person=person)
user.set_password(password)
user.save(using=self._db)
return user
class User(AbstractBaseUser):
## the id of the user. unique through the application
user_id = models.AutoField(primary_key=True)
## the name of the user. unique through the application
username = models.CharField(max_length=32, unique=True)
## the date when the user was created
created = models.DateTimeField()
## iff this is true the user must set a new password at next login
must_change_password = models.BooleanField(default=True)
## iff true the user is marked as deleted and can not login
deleted = models.BooleanField(default=False)
## iff true the user is admin and has all permissions. use with care!
is_admin = models.BooleanField(default=False)
## reference to the person entity that is linked to this specific user
person = models.ForeignKey(Person)
## indicates if the user is active or not
active = models.BooleanField(default=True)
## define the user manager class for User
objects = UserManager()
# necessary to use the django authentication framework: this field is used as username
USERNAME_FIELD = 'username'
我在行中收到 NoneType 错误user = self.model(..)
在 UserManager 的 create_user() 方法中
要创建新用户,您不应调用UserManager.create_user(...)
。相反,你应该使用:
from django.contrib.auth import get_user_model
get_user_model().objects.create_user(...)
这就是 Django 管理器的工作方式。您可以阅读文档here https://docs.djangoproject.com/en/dev/topics/db/managers/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)