Django密码验证无效

时间:2017-12-31 04:32:08

标签: python django

我正在使用自己的自定义用户模型,但我继承了django.contrib.auth用户模型。我有一个用户名,电子邮件和密码字段。我没有明确添加密码字段,因为默认情况下它会被继承添加。当我尝试通过命令行创建超级用户时,正常的默认Django密码验证工作正常。但是,当我有一个注册表单时,它不是。单击“提交”时,电子邮件和用户名验证工作正常,但没有密码验证。我可以输入我想要的任何内容,它会接受密码。

这是我的forms.py

class RegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    username    = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'}))
    email       = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'}))
    password    = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'}))

以下是我的观点:

class RegisterView(SuccessMessageMixin, View):
    form_class = RegisterForm
    template_name = 'oauth/auth_form.html'
    success_message = "You have successfully created an account!"

    # Display blank form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit=False) # Do not save to table yet

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            user.set_password(password)
            user.save()

            # Let's try to login the user
            user = authenticate(username=username, password=password)

            if user is not None:

                    login(request, user)
                    return redirect('profiles: index')

        return render(request, self.template_name, {'form': form})

如何使用Django的默认密码验证来正确验证密码字段?

1 个答案:

答案 0 :(得分:6)

Django有integrate password validation的一些工具。最简单的方法是在表单的字段特定validate_password方法中调用clean_password函数,但由于您需要一些验证器的用户实例,我将在视图中演示它的用法:

from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError

class RegisterView(SuccessMessageMixin, View):
    # ...
    def post(self, request):

        if form.is_valid():
            user = form.save(commit=False) # Do not save to table yet
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            try:
                validate_password(password, user)
            except ValidationError as e:
                form.add_error('password', e)  # to be displayed with the field's errors
                return render(request, self.template_name, {'form': form})
            # ...

        return render(request, self.template_name, {'form': form})