【问题标题】:Django does not raise validation error username and passwordDjango 不会引发验证错误用户名和密码
【发布时间】:2020-01-13 18:03:33
【问题描述】:

Django 不会引发针对用户名和密码添加到 forms.py 的验证错误。它确实会根据核心密码验证显示密码验证错误,但不会检查密码是否相同。这一切都基于 Django 中的基本用户模型。

您能帮我弄清楚为什么表单验证不起作用吗?我收到以下错误是用户名已在使用中或密码不匹配:“表单无效。” 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>

【问题讨论】:

  • 你是如何在模板中渲染的?
  • @Matthew 添加了模板。

标签: django django-forms


【解决方案1】:

大部分代码都是不必要的。您不应该在您的视图中提出验证错误;所有验证都已在表单中完成。你的观点应该是:

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 }} 显示模板中的任何错误。

【讨论】:

  • 这对我不起作用。我在模板的 {{ form }} 下添加了 {{ form.errors }}。相反,如果我有两个不同的密码,它会给我相同的“表单不是无效的”
  • 不可能发生这种情况,因为我的代码不包含您的版本中引发该消息错误的部分。
  • 你的权利我没有删除那行。我仍然收到一个错误:它永远不会让我添加新的用户名。无论用户名是什么,它都会显示“用户名已存在”。
  • clean_username中,exists是一个需要调用的方法:if user_name.exists():
  • 谢谢!出于某种原因,我仍然遇到同样的问题 - “相同的密码错误”永远不会出现,它会转到 next.html。
猜你喜欢
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-15
  • 2018-05-26
  • 2013-12-26
相关资源
最近更新 更多