You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义登录表单is_valid()验证失败求助

Django自定义用户模型登录表单is_valid验证失败问题修复

问题分析

你的代码存在几个关键错误,直接导致表单无法通过验证:

  • clean方法缩进错误:被错误嵌套在Meta类内部,Django无法识别该清洗逻辑
  • 属性名拼写错误:将cleaned_data写成clean_data,将password写成pasword
  • clean方法内调用self.is_valid():会触发无限循环(is_valid()本身会调用clean流程)
  • 视图逻辑错误:POST请求验证失败时未将错误表单传入上下文,且GET请求分支的错误提示逻辑混乱

修复后的代码

1. 登录表单代码修复

class UserLoginForm(forms.ModelForm):
    password = forms.CharField(label="Password", widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('email', 'password')
        widgets = {
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'password': forms.PasswordInput(attrs={'class': 'form-control'}),
        }

    # 将clean方法移至Meta类外部,与Meta同级
    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')

        if email and password:
            user = authenticate(email=email, password=password)
            if not user:
                raise forms.ValidationError("Invalid Credentials")
        return cleaned_data

2. 登录视图代码修复

def login_view(request):
    context = {}
    if request.method == 'POST':
        form = UserLoginForm(data=request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = authenticate(request, email=email, password=password)
            if user is not None:
                login(request, user)
                return redirect("logistics:dashboard")
        # 验证失败时,将带错误信息的表单传入上下文
        context["loginform"] = form
    else:
        # GET请求初始化空表单
        form = UserLoginForm()
        context["loginform"] = form

    return render(request, 'dashboard/authentication-login.html', context)

额外说明

  • 优先使用form.cleaned_data获取值,而非直接读取request.POST,确保数据经过表单清洗验证
  • clean方法必须先调用super().clean()获取标准清洗后的数据集,这是Django表单的标准流程
  • 增加if email and password:判断,避免字段为空时引发额外错误

内容的提问来源于stack exchange,提问作者Kevnlan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:08:23