是否需要在 Django 中为自定义用户模型制作自定义管理器
Is it required to make a custom manger for a custom user model in django
我正在按照这两个教程 (tutorial-1 and tutorial-2) 使用 AbstractBaseUser
和 PermissionsMixin
制作自定义用户模型。
到目前为止的模型:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', unique=True, db_index=True)
username = models.CharField('username', unique=True, db_index=True)
joined = models.DateField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
def __unicode__(self):
return self.email
现在让我感到困惑的是,在tutorial-1中,作者没有为自定义用户模型制作任何自定义管理器。相反,他使用表单来创建用户。
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(label = 'Email')
password1 = forms.CharField(widget = forms.PasswordInput(), label = "Password")
password2 = forms.CharField(widget = forms.PasswordInput(), label = 'Retype password')
class Meta:
model = User
fields = ['email', 'username', 'password1', 'password2']
def clean(self):
"""
Verify that the values entered into the password fields match
"""
cleaned_data = super(RegistrationForm, self).clean()
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise ValidationError("Password don't match.")
return self.cleaned_data
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
但是在tutorial-2中,它的作者为自定义用户模型做了一个自定义管理器。
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
参考Django Docs,有一个自定义用户模型的例子,它使用了自定义管理器。我的问题是,是否可以不创建任何其他自定义管理器,如果不行,创建自定义管理器有什么用?
我认为这是 the docs 中适合您的相关部分:
You should also define a custom manager for your User model. If your User model defines username
, email
, is_staff
, is_active
, is_superuser
, last_login
, and date_joined
fields the same as Django’s default User
, you can just install Django’s UserManager
; however, if your User model defines different fields, you will need to define a custom manager that extends BaseUserManager
providing [the create_user()
and create_superuser()
methods].
文档中的示例需要定义一个自定义管理器,以便它可以设置 date_of_birth
字段。
教程中的示例似乎需要自定义管理器,因为它使用 email
作为唯一标识符,并且没有单独的用户名字段。
我正在按照这两个教程 (tutorial-1 and tutorial-2) 使用 AbstractBaseUser
和 PermissionsMixin
制作自定义用户模型。
到目前为止的模型:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', unique=True, db_index=True)
username = models.CharField('username', unique=True, db_index=True)
joined = models.DateField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
def __unicode__(self):
return self.email
现在让我感到困惑的是,在tutorial-1中,作者没有为自定义用户模型制作任何自定义管理器。相反,他使用表单来创建用户。
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(label = 'Email')
password1 = forms.CharField(widget = forms.PasswordInput(), label = "Password")
password2 = forms.CharField(widget = forms.PasswordInput(), label = 'Retype password')
class Meta:
model = User
fields = ['email', 'username', 'password1', 'password2']
def clean(self):
"""
Verify that the values entered into the password fields match
"""
cleaned_data = super(RegistrationForm, self).clean()
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise ValidationError("Password don't match.")
return self.cleaned_data
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
但是在tutorial-2中,它的作者为自定义用户模型做了一个自定义管理器。
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
参考Django Docs,有一个自定义用户模型的例子,它使用了自定义管理器。我的问题是,是否可以不创建任何其他自定义管理器,如果不行,创建自定义管理器有什么用?
我认为这是 the docs 中适合您的相关部分:
You should also define a custom manager for your User model. If your User model defines
username
,is_staff
,is_active
,is_superuser
,last_login
, anddate_joined
fields the same as Django’s defaultUser
, you can just install Django’sUserManager
; however, if your User model defines different fields, you will need to define a custom manager that extendsBaseUserManager
providing [thecreate_user()
andcreate_superuser()
methods].
文档中的示例需要定义一个自定义管理器,以便它可以设置 date_of_birth
字段。
教程中的示例似乎需要自定义管理器,因为它使用 email
作为唯一标识符,并且没有单独的用户名字段。