我正在使用Django 1.8。在按照如何自定义用户模型的教程后,我决定使用自定义用户模型制作应用程序。我的CustomUser模型看起来像 -
class CustomUser(AbstractBaseUser):
first_name = models.CharField(max_length=100,blank=True)
last_name = models.CharField(max_length=100,blank=True)
college = models.CharField(max_length=200,blank=True)
email = models.EmailField(unique=True,blank=False)
date_joined = models.DateTimeField(_('date joined'), default=datetime.now())
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name']
objects = CustomUserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s/" % urlquote(self.email)
def get_full_name(self):
"""
Returns the first name plus the last name , with a space in between
"""
full_name = '%s %s' % (self.first_name,self.last_name)
return full_name.strip()
我的CustomUserManager类就是这个(虽然这里不重要) -
class CustomUserManager(BaseUserManager):
def _create_user(self,email,password,is_staff,is_superuser,**extra_fields):
"""
Creates and saves a User with the given email and password
"""
t = datetime.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,is_staff=is_staff,is_active=True,is_superuser=is_superuser,
last_login=t,date_joined=t,**extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self,email,password=None,**extra_fields):
return self._create_user(email,password,False,False,**extra_fields)
def create_superuser(self,email,password=None,**extra_fields):
print "Inside Superuser"
return self._create_user(email,password,True,True,**extra_fields)
我已将相关设置 - AUTH_USER_MODEL和AUTHENTICATION_BACKENDS添加到settings.py文件中。
最重要的是,我的自定义注册表单如下所示 -
class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and password
"""
def __init__(self,*args,**kargs):
super(CustomUserCreationForm,self).__init__(*args,**kargs)
#print self.fields
del self.fields['username']
class Meta:
model = CustomUser
fields = ('email',)
我在这里提到我的模型将是CustomUser。你可以看到我的自定义表单继承自内置的UserCreation表单。为方便起见,我也在这里发布UserCreationFrom类 -
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("username",)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
我对此有一些疑问.UserCreationForm将模型设置为User,这是默认的User模型(来自django.contrib.auth.models import User);
但在我的CustomForm的元类中,我提到的模型等于我的CustomUser。
当我打印UserCreationForm返回的字段时,它给出了 - username,password1,password2。'username'字段的存在是UserCreationForm使用'User'模型并添加'username'字段的证据,后来我在我的自定义表单中删除了
我还在自定义表单的字段中添加了“电子邮件”,但电子邮件选项未在我的注册页面中呈现。我正在以正确的方式创建自定义注册表单吗? 如果没有,那么应该如何在我的自定义注册表单中呈现电子邮件字段。
答案 0 :(得分:1)
from .models import CustomUser
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput)
class Meta:
model = CustomUserModel
# Note - include all *required* CustomUser fields here,
# but don't need to include password1 and password2 as they are
# already included since they are defined above.
fields = ("email",)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
msg = "Passwords don't match"
raise forms.ValidationError("Password mismatch")
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user