我正在用Django 1.5构建一个web应用程序。我正在使用一个自定义用户模型和一个自定义用户管理器。 我遵循了Django官方文档的说明和示例。
现在,当我试图通过UserManager.create_user(...)
创建一个新用户时,我得到了一个None type错误:似乎UserManager的属性模型是None类型的。
我认为我在用户模型中正确地设置了UserManager(objects = UserManager()
)
我真的不知道我错在哪里。布思我的编码伙伴和我是新的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'
我在UserManager的create_user()方法的第user = self.model(..)
行得到了非类型错误
要创建新用户,不应调用
UserManager.create_user(...)
。相反,您应该使用:这就是django经理的工作方式。你可以阅读文档here
我不得不补充一个答案,因为我没有足够的代表来评论。但是@Aldarund的答案中的链接根本没有描述get_user_model()的用法。但是,this link应该会有帮助。。。
我在保存自定义用户模型时也遇到了问题,我花了一段时间才将其计算为
我认为你的代码中最重要的一行是:
在用户类中,因此为了保存新用户,您需要调用
“
objects
”是调用UserManager
类的项,在django
中称为管理器相关问题 更多 >
编程相关推荐