在我的表单中,我添加了一个名为'password_confirm'的变量。但鉴于此,django不知道。 在html文件中,我手动创建了一个表单。
我的表单代码:
class UserRegisterForm(forms.Form):
name = forms.CharField(required=True,)
family = forms.CharField(required=True)
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
password = forms.CharField(required=True, widget=forms.PasswordInput())
password_confirm = forms.CharField(required=True, widget=forms.PasswordInput())
type = forms.CharField(max_length=1)
def clean_password(self, *args, **kwargs):
pas1 = self.cleaned_data.get('password')
pas2 = self.cleaned_data.get('password_confirm')
if pas1 != pas2:
raise forms.ValidationError("password and confirmation not matched!")
return super(UserRegisterForm, self).clean()
def clean_email(self):
email_qs = User.objects.filter(email=self.cleaned_data['email'])
if email_qs.exists():
raise forms.ValidationError("this email already exists!")
这是我的表单元素:
<input type="password" name="password_confirm" id="confirm-password" tabindex="8" class="form-control" placeholder="confirm" dir="rtl"/>
这是观点:
def register_view(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/')
form = UserRegisterForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
password = form.cleaned_data['password']
user.set_password(password)
user.save()
profile = Profile()
profile.name = form.cleaned_data['name']
profile.family = form.cleaned_data['family']
profile.name = form.cleaned_data['email']
profile.type = form.cleaned_data['type']
profile.save()
login(request, user)
return HttpResponseRedirect('/')
return render(request, 'accounts/signup.html', {'form': form})
这是错误: / register /的KeyError 'password_confirm'
问题是什么?
答案 0 :(得分:1)
表单的字段顺序很重要。由于password
方法password_confirm
中的clean_password
之前定义的password_confirm
为空。
您需要在clean_password_confirm
方法中执行密码检查,只需将其重命名为:
def clean_password_confirm(self, *args, **kwargs):
...