Django modelform how to add a confirm password field?

前端 未结 4 676
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 01:40

Here I need to add an extra confirmation password in my form.I used Django\'s modelform. I also need to validate both passwords. It must raise a validation error if

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 02:10

    You can have a look at how Django does it for 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
    

    Here password2 refers to the confirm_password field, under the assumption that it appears after the password field. Trying to use the same implementation for clean_password may lead to an error that the confirm_password data wasn't found.

    This has the advantage that you're raising the error for a particular Field, instead of the whole form, which you can then render appropriately in your template.

    However, if you're trying to validate data across multiple fields, the documentation advises overriding the clean() method, as answered by Savai.

    The source code is available here.

提交回复
热议问题