表单验证错误未显示在模板中

时间:2018-01-14 17:54:57

标签: python django django-forms

我正在创建一个注册用户的表单,我添加了验证错误以检查数据库中是否已存在该电子邮件。但是,当您输入已存在于数据库中的电子邮件时,表单不会显示错误,只会重置。

forms.py:

class SignUpForm(UserCreationForm):
    institute = forms.CharField(max_length=255)
    def __init__(self, *args, **kwargs):
        super(SignUpForm, self).__init__(*args, **kwargs)
        # Making name required
        self.fields['email'].required = True
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'institute' )

    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            match = User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError("Cannot use this email. It's already registered")
        return email

这是我的views.py:

def register(request):

if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
        user = form.save()
        user.refresh_from_db()  # load the profile instance created by the signal
        user.profile.institute = form.cleaned_data.get('institute')
        print(user.profile.institute)
        user.save()
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(username=user.username, password=raw_password)
        login(request, user)
        return render(request,'home.html')

form = SignUpForm()
context = {
    'form' : form,
}

return render(request,'register.html', context)

我正在使用脆弱的表格

1 个答案:

答案 0 :(得分:0)

要显示验证错误,您需要将同一表单重新放入context字典。

在您的特定示例中,如果表单无效,则外部if - 语句结束,并使用form= SignUpForm()创建新表单并添加到呈现的上下文中。因此,如果返回的表单无效,上面的代码只会向上下文返回一个新的空表单。

调整您的代码,以便将无效表单传递给响应。然后你会看到错误:

if request.method == 'POST':
    form = SignUpForm(request.POST) 
    if form.is_valid():
        user = form.save()
        user.refresh_from_db() # load the profile instance created by the signal
        user.profile.institute = form.cleaned_data.get('institute')
        print(user.profile.institute)     
        user.save() 
        raw_password = form.cleaned_data.get('password1') 
        user = authenticate(username=user.username, password=raw_password)
        login(request, user) 
        return render(request,'home.html')
    else:  # if the form is not valid, pass the invalid form in the context
        return render(request,'register.html', { 'form' : form, })
form = SignUpForm() 
context = { 'form' : form, }
return render(request,'register.html', context