form.py 中的覆盖 clean() 函数在 Django 中的身份验证在 views.py 中不起作用



我正在用Django练习认证功能。

它可以在clean()函数中不将cleaned_data分配给super().clean(),但我不知道它是否正常工作,所以为了检查我遇到的错误,我在文件views.py中编写了print('not valid'),并将其打印在终端中。在form.is_valid():部分似乎没有进入下一步。

is_valid()部分我应该改变哪一部分?

我尝试在同一行中使用print(form.errors.as_data)打印('not valid')。显示{'email': ['Custom user with this Email address already exists.']}

文件 form.py

class AuthenticationForm(forms.ModelForm):
    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    class Meta:
        model = CustomUser
        fields = ['email', 'password']
    def clean(self):
        cleaned_data = super(AuthenticationForm, self).clean()
        email    = cleaned_data.get('email')
        password = cleaned_data.get('password')
        if not authenticate(email=email, password=password):
            print('not authenticated')
            raise forms.ValidationError("It's invalid.")
        return cleaned_data

文件 views.py

def login_view(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if form.is_valid():
            email       = form.cleaned_data.get('email')
            password    = form.cleaned_data.get('password')
            user        = authenticate(email=email, password=password)
            if user is not None:
                login(request, user)
                return redirect('blogs:home')
            else:
                return redirect('accounts:login')
        else:
            print('not vailid')
    context = {'form':form}
    return render(request, 'accounts/login.html', context)

您的认证表单不应该从ModelForm继承。每次有人尝试进行身份验证时,ModelForm的默认save()方法将尝试使用给定的电子邮件地址创建一个新用户。这就是为什么您会看到错误Custom user with this Email address already exists.

相反,从django.contrib.auth.forms.AuthenticationForm:

继承您的表单
from django.contrib.auth import forms
class AuthenticationForm(forms.AuthenticationForm):
    def clean(self):
        cleaned_data = super(AuthenticationForm, self).clean()
        email    = cleaned_data.get('email')
        password = cleaned_data.get('password')
        if not authenticate(email=email, password=password):
            print('not authenticated')
            raise forms.ValidationError("It's invalid.")
        return cleaned_data

请注意,Django的默认auth视图会为你处理所有这些,所以在实践中你不需要手动进行身份验证。

相关内容

  • 没有找到相关文章

最新更新