Django不会提高验证错误的用户名和密码

时间:2019-09-11 21:16:02

标签: django django-forms

Django不会在用户名和密码中添加到forms.py中的验证错误。它确实会基于核心密码验证提出密码验证错误,但不会检查密码是否相同。这全部基于Django中的基本User模型。

您能帮我弄清楚为什么表单验证不起作用吗?我收到以下错误是用户名已被使用或密码不匹配:“表单无效”。 if语句if form.is_valid():失败。

Forms.py:

class CustomUserCreationForm(forms.ModelForm):
    username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"}))
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"}))
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"}))

    class Meta:
        model = User
        fields = ['username']

    def clean_password(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords do not match")
        return password2

    def clean_username(self):
        username = self.cleaned_data.get('username')
        user_name = User.objects.filter(username=username)
        if user_name.exists:
            raise forms.ValidationError("Username already exists. Please try again.")
        return username

    def save(self, commit=True):
        user = super(CustomUserCreationForm, self).save(commit=False)
        user.username = self.cleaned_data['username']
        user.set_password(self.cleaned_data['password1'])

        if commit:
            user.save()
        return user

Views.py:

def payments(request):
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            password1 = form.cleaned_data['password1']
            #this works to do Django core validation, but not form validation
            try:
                validate_password(password1)
            except ValidationError as e:
                form.add_error('password1', e) # to be displayed with the field's errors
            username = form.cleaned_data['username']
            #this does not work
            try:
                validate_username(username)
            except ValidationError as e:
                form.add_error('username', e)
            user = form.save(commit=False)
            user.is_active = True
            user.set_password(form.cleaned_data['password1'])
            user.save()          
        else:
            raise ValidationError("Form is not valid. Try Again.")
            return render(request, 'next.html', {'form': form})

    else:
        form = CustomUserCreationForm()
return render(request, 'next.html', {'form': form})

模板

<div class="col-md-6 mb-4">
                <h3 class="font-weight-bold">Register now</h3>
                <div class="card">
                    <div class="card-body">
                        <p>Already have an account? <a href="{% url 'login' %}"> Login</a></p>
                        <form method="POST" class="post-form">
                            {% csrf_token %}
                            {{ form }}
                            <div class="text-center mt-4">
                                <button type="submit" class="btn btn-secondary">Register</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

1 个答案:

答案 0 :(得分:0)

大多数代码都是不必要的。您不应在视图中引发验证错误;所有验证已在表格中完成。您的视图应为:

def payments(request):
    if request.method == "POST":
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            password1 = form.cleaned_data['password1']
            user = form.save(commit=False)
            user.is_active = True
            user.set_password(form.cleaned_data['password1'])
            user.save()
            return redirect("/")
    else:
        form = CustomUserCreationForm()
    return render(request, 'next.html', {'form': form}

,您可以通过{{ form.errors }}在模板中显示任何错误。