我正在尝试构建这样的自定义用户模型:
suitcase = []
# an element is added
suitcase.append('sunglasses')
suitcase.append('sungses')
suitcase.append('sungsses')
suitcase.append('sungl')
list_length = len(suitcase)
print ("There are %d items in the suitcase." % (list_length))
print (suitcase)
要注册新用户,我创建了此表单:
class UserTest(models.Model):
#username=models.EmailField()
username=models.OneToOneField(User, on_delete=models.CASCADE)
email=models.EmailField(User)
# password=models.CharField(max_length=40)
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
birthday=models.DateField(auto_now=False, null=True, blank=True)
# USERNAME_FIELD='username'
def __str__(self):
return self.username.username
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile=UserTest.objects.create(username=kwargs['instance'])
post_save.connect(create_profile,sender=User)
这工作正常,但DateField显示为文本字段。我以前使用过这样的自定义DateInput:
class UserRegisterForm(forms.ModelForm): #neuen "normalen" Nutzer registrieren
username=forms.EmailField(label='Email address')
email=forms.EmailField(label='Confirm Email')
password=forms.CharField(widget=forms.PasswordInput)
password2=forms.CharField(widget=forms.PasswordInput)
first_name=forms.CharField(label='First Name')
last_name=forms.CharField(label='Last Name')
birthday=forms.DateField(label='Birthday')
class Meta:
model=User
fields=[
'username',
# 'username2',
'email',
'password',
'password2',
'first_name',
'last_name',
'birthday',
]
def clean(self,*args,**kwargs):
username=self.cleaned_data.get("username")
email=self.cleaned_data.get("email")
password=self.cleaned_data.get("password")
password2=self.cleaned_data.get("password2")
username=self.cleaned_data.get("username")
birthday=self.cleaned_data.get("birthday")
if username!=email:
raise forms.ValidationError("Emails must match")
email_qs=User.objects.filter(username=username)
if email_qs.exists():
raise forms.ValidationError("This Email has already been registered")
if password!=password2:
raise forms.ValidationError("Passwords must match")
return super(UserRegisterForm,self).clean(*args,**kwargs)
这样的称呼:
class DateInput(forms.DateInput):
input_type = 'date'
现在我在models.py中遇到错误:
class UserRegisterForm(forms.ModelForm):
username=forms.EmailField(label='Email address')
email=forms.EmailField(label='Confirm Email')
password=forms.CharField(widget=forms.PasswordInput)
password2=forms.CharField(widget=forms.PasswordInput)
first_name=forms.CharField(label='First Name')
last_name=forms.CharField(label='Last Name')
class Meta:
model=User
fields=[
'username',
'email',
'password',
'password2',
'first_name',
'last_name',
'birthday',
]
widgets = {
'birthday': DateInput()
}
这对我来说很奇怪,因为只要我坚持使用默认小部件,就可以知道该字段。 我阅读了文档并在Google周围搜索,但找不到解决方案。 现在,我要问的是在使用自定义用户模型时如何使用小部件,以及为什么Django的行为方式如此。如果你们中的任何一个都可以为我提供合适的教程,那就太好了。
预先感谢