/ registration / value'password1'的KeyError

时间:2016-01-23 10:37:51

标签: django django-forms django-authentication

我使用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['password']
                password1 = self.cleaned_data['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)

如果我填写密码字段是对还是错,我有同样的错误KeyError at /registration/Exception Value: 'password1'。谢谢你的回答。

3 个答案:

答案 0 :(得分:1)

对于模型表单,如果指定非模型字段(如password1),则必须在表单元类中提及fields属性。

模型表单仅包含现有模型字段。在模型表单元类中添加它:

class Meta:
    model = UserProfile
    fields = ('username', 'email', 'password', 'password1')

答案 1 :(得分:1)

password1无法保证在调用cleaned_data时添加到clean_password()。对于需要存在多个字段的任何验证,您应该使用常规clean()方法进行验证。

答案 2 :(得分:1)

Django用户已经无需添加电子邮件(请参阅https://docs.djangoproject.com/en/1.9/topics/auth/default/#user-objects

class UserProfile(models.Model):

        user = models.OneToOneField(User)
        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

此外,您还需要在表单中为password1添加clean()作为密码。