我正在遵循本教程(http://musings.tinbrain.net/blog/2014/sep/21/registration-django-easy-way/)在 Django 中创建用户注册模型。
我知道类用户管理器正在覆盖默认的用户模型。但是,我不明白这个特定的部分。
官方的 Django 文档没有解释这意味着什么 - 它只显示了完整的代码。
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/
需要澄清一下这里发生了什么。
user = self.model(email=self.normalize_email(email), is_active=True, **kwargs)
user.set_password(password)
user.save(using=self._db)
这是整个班级。
class UserManager(BaseUserManager):
def create_user(self, email, password, **kwargs):
user = self.model(email=self.normalize_email(email), is_active=True, **kwargs)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(email=email, is_staff=True, is_superuser=True, is_active=True, **kwargs)
user.set_password(password)
user.save(using=self._db)
return user
在内存中创建用户实例。 填充self.model
属性,然后在模型类中实例化模型管理器:
class MyUser(AbstractBaseUser):
objects = UserManager() # here the `objects.model` is set to `MyUser`
规范化电子邮件意味着域部分为小写。 is_active
True
,因此用户可以登录。 如果任何其他字段作为关键字参数传递给create_user()
,则将这些字段分配给创建的用户。
user = self.model(email=self.normalize_email(email), is_active=True, **kwargs)
设置哈希密码。
user.set_password(password)
将用户实例保存到数据库中。
user.save(using=self._db)