我使用User
的其他字段创建了一个新模型。
models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
email = models.CharField(max_length=50)
birthday = models.DateField(u'Birthday', blank=True, null=True)
avatar = models.ImageField(Avatar', upload_to='profile/avatar', blank=True)
def __unicode__(self):
return self.user
然后我为用户创建注册表单:
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'Enter Your Username'))
email = forms.EmailField(label=(u'Enter Your E-mail'))
password = forms.CharField(label=(u'Enter Password'), widget=forms.PasswordInput(render_value=False))
password1 = forms.CharField(label=(u'Verify Your Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = UserProfile
exclude = ('user',)
def clean_email(self):
email = self.cleaned_data['email']
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError("User with same e-mail is already exist, please type another email")
def clean_password(self):
password = self.cleaned_data.get('password')
password1 = self.cleaned_data.get('password1')
if not password1:
raise forms.ValidationError("You have ti verify your password")
if password != password1:
raise forms.ValidationError("Your passwords doesn't match")
return password1
这是我对注册页面的看法:
def UserProfileRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/info/')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password'])
user.save()
user_profile = UserProfile(user=user)
user_profile.save()
return HttpResponseRedirect('/info/')
else:
return render(request, 'profiles/registration.html', {'form':form})
else:
form = RegistrationForm()
context = {'form':form}
return render (request, 'profiles/registration.html', context)
看起来像我的html页面:
<form action="." method="POST">
{% csrf_token %}
{% if form.username.errors %}
{% for error in form.username.errors %}
<p>This field is required</p>
{% endfor %}
{% endif %}
{{ form.username.label_tag}}
{{ form.username }}
{% if form.email.errors %}
{% for error in form.email.errors %}
<p>This field is required</p>
{% endfor %}
{% endif %}
{{ form.email.label_tag }}
{{ form.email }}
{% if form.password.errors %}
{% for error in form.password.errors %}
<p>This field is required</p>
{% endfor %}
{% endif %}
{{ form.password.label_tag }}
{{ form.password }}
{% if form.password1.errors %}
{% for error in form.password1.errors %}
<p>This field is required</p>
{% endfor %}
{% endif %}
{{ form.password1.label_tag }}
{{ form.password1 }}
</form>
但是当我尝试注册用户时,我有错误
此字段是必填字段
表示password
字段。我不明白为什么。
如果你帮助我,我会很高兴。
答案 0 :(得分:3)
而不是print predefind错误消息尝试打印实际错误消息。
而不是
<p>This field is required</p>
使用
<p>{{ error }}</p>
答案 1 :(得分:1)
在clean_password方法中,验证后返回password1。您应该返回密码对象。对于模型表格,这很重要。
保存模型时,表单字段名称用于决定哪个模型字段是哪个表单字段。