我有一个表单来使用用户模型注册用户。
形式:
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password']
模板:
{% block content %}
<p>Register</p>
{{ user_form.as_p }}
{% endblock %}
views.py:
def register_view(request):
if request.method == "POST":
user_form = UserForm(request.POST)
if user_form.is_valid:
user = user_form.save()
return HttpResponseRedirect('/account/registered/')
else:
user_form = UserForm()
return render(request, 'register_view.html', {
'user_form': user_form
})
但我需要在表单中添加其他功能:
我尝试在字段列表中设置两次电子邮件字段:
fields = ['first_name', 'last_name', 'username', 'email', 'password']
但它只显示一个电子邮件字段。
如何根据我的需要使用ModelForm自定义表单?
更新
使用答案更新了我的表单,但现在我收到错误:
/ account / register /
中的KeyError&#39; confirm_email&#39;
更新表格:
class UserForm(forms.ModelForm):
confirm_email = forms.EmailField(label="Confirm email")
def clean(self):
email = self.cleaned_data['email']
confirm_email = self.cleaned_data['confirm_email']
password = self.cleaned_data['password']
if email != confirm_email:
raise ValidationError({'confirm_email': "Both email doesn't match."})
if len(password) < 8:
raise ValidationError({'password': "Password should be of minimum 8 characters."})
return super(UserForm, self).clean()
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'confirm_email', 'password']
答案 0 :(得分:1)
您应该在表单中创建第二个字段email
并验证两个电子邮件在clean
方法中是否相同,如下所示:
class UserForm(forms.ModelForm):
confirm_email = forms.EmailField(label="Confirm email")
def clean(self):
email = self.cleaned_data['email']
confirm_email = self.cleanded_data['confirm_email']
if email != confirm_email:
raise ValidationError({'confirm_email': "provided email doesn't match with above one"})
return super(UserForm, self).clean()
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password']
你应该用你的密码做同样的事情。请务必使用set_password
方法为用户保存实际密码,不要将原始密码存储在数据库中。