python-3.x Django modelform如何添加确认密码字段?

wnavrhmk  于 2023-01-10  发布在  Python
关注(0)|答案(5)|浏览(124)

这里我需要在我的表单中添加一个额外的confirmation password。我使用了Django的modelform。我还需要验证两个密码。如果password1 != password2,它必须引发验证错误。
Here is my forms.py:

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

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

class UserProfileForm(forms.ModelForm):
    YESNO_CHOICES = (('male', 'male'), ('female', 'female'))
    sex = forms.TypedChoiceField(choices=YESNO_CHOICES, widget=forms.RadioSelect)
    FAVORITE_COLORS_CHOICES=(('red','red'),('blue','blue'))
    favorite_colors = forms.MultipleChoiceField(required=False,widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)
    dob = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), 
                                 input_formats=('%d/%m/%Y',))

    class Meta:

        model=UserProfile
        fields=('phone','picture','sex','favorite_colors','dob')

下面是我的注册函数:

def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)


        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
            profile.save()
            registered = True
        else:
            print user_form.errors, profile_form.errors
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    return render(request,
            'mysite/register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
4si2a6ki

4si2a6ki1#

clean的用法如下

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())
    confirm_password=forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model=User
        fields=('username','email','password')

    def clean(self):
        cleaned_data = super(UserForm, self).clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")

        if password != confirm_password:
            raise forms.ValidationError(
                "password and confirm_password does not match"
            )
yeotifhr

yeotifhr2#

def clean(self):
    cleaned_data = super(UserAccountForm, self).clean()
    password = cleaned_data.get("password")
    confirm_password = cleaned_data.get("confirm_password")

    if password != confirm_password:
        self.add_error('confirm_password', "Password does not match")

    return cleaned_data
uajslkp6

uajslkp63#

在www.example.com上试试这个forms.py:

class UserForm(forms.Form):
    password = forms.CharField(widget=forms.PasswordInput())
    password_confirm = forms.CharField(widget=forms.PasswordInput())

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

这个在views.py:

if user_form.is_valid() and profile_form.is_valid() and user_form.cleaned_data['password'] == user_form.cleaned_data['password_confirm']:
    ...
elif user_form.data['password'] != user_form.data['password_confirm']:
    user_form.add_error('password_confirm', 'The passwords do not match')
vsnjm48y

vsnjm48y4#

你可以看看Django是如何为UserCreationForm做的。

def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        return password2

这里password2指的是confirm_password字段,假设它出现在password字段之后,尝试对clean_password使用相同的实现可能会导致找不到confirm_password数据的错误。
这样做的好处是,您可以为特定的Field而不是整个表单引发错误,然后可以在模板中适当地呈现该表单。
但是,如果您试图验证多个字段中的数据,文档建议覆盖clean()方法,正如Savai所回答的那样。
源代码可在here上获得。

whitzsjs

whitzsjs5#

确认密码已在UserCreationForm中可用

class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

这将在调用form.is_valid()时自动验证password1==password2
在这里,我只将电子邮件作为一个单独的表单参数,以便进一步清理和验证

相关问题