我正在使用AbstractBaseUser
和PermissionsMixin
遵循这两个教程(tutorial-1和tutorial-2)制作自定义用户模型。
这是迄今为止的模型:
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中,作者没有为自定义 User 模型制作任何自定义管理器。相反,他使用表单来创建用户。
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中,它的作者为自定义 User 模型制作了一个自定义管理器。
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,有一个自定义用户模型的示例,它使用自定义管理器。我的问题是,是否可以不创建任何其他自定义管理器,如果不是,创建自定义管理器有什么用?