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

Django 5.1.x中UserCreationForm无法允许空密码的问题求助

Django 5.1.x中UserCreationForm无法允许空密码的问题求助

我正在把一个Django 3.0的项目升级到5.1,一直是逐个小版本慢慢推进的,到目前为止都还算顺利。

不过从Django 5.0升级到5.1之后,我的「创建新用户」页面出现了行为变化——这个页面用的是UserCreationForm,原本允许提交空密码,没有密码的话就自动生成随机密码。

现在如果我提交空密码的表单,密码字段会弹出「必填字段」的错误,但明明我已经把这两个字段都显式设置为required=False了。

我看到Django 5.1.0和5.1.1版本里UserCreationForm有更新,尝试过用AdminUserCreationForm,还把usable_password字段设为None,但还是没法像之前那样允许空密码。

有没有大佬有解决思路?

环境

  • Python 3.12.8
  • Django 5.1.5
  • Crispy Forms 2.3

简化后的代码

from django.contrib.auth.forms import AdminUserCreationForm
from crispy_forms.helper import FormHelper

class SignupForm(AdminUserCreationForm): # 之前用的是UserCreationForm

    usable_password = None # 新增的设置

    # 表单字段
    sharedaccountflag = forms.ChoiceField(
                            label = 'Cuenta compartida', 
                            required = True
                        )

    # 构造方法
    def __init__(self, *args, **kwargs):
                
        # 调用父类构造方法
        super(SignupForm, self).__init__(*args, **kwargs)

        # 设置密码字段为可选
        self.fields['password1'].required = False
        self.fields['password2'].required = False

        # 设置表单助手属性
        self.helper = FormHelper()
        self.helper.form_tag = False

    # 指定模型和表单包含的字段
    class Meta:
        model = get_user_model()
        fields = ('password1', 'password2', 'sharedaccountflag')

截图

提交空密码时的错误提示


更新

我参考了Serhii的示例修改了代码,让常规验证在合适的情况下才触发,同时改回使用UserCreationForm:

class SignupForm(UserCreationForm):

    # 重写默认验证逻辑,允许空密码(适配Django 5.1的变化)
    def validate_passwords(
        self, 
        password1_field_name = "password1", 
        password2_field_name = "password2"
    ):  
    
        # 获取密码值
        password1 = self.cleaned_data.get(password1_field_name)  
        password2 = self.cleaned_data.get(password2_field_name)  

        # 如果密码字段非必填且没有输入任何内容,跳过验证
        if (
            not self.fields[password1_field_name].required and 
            not self.fields[password2_field_name].required and
            not password1.strip() and 
            not password2.strip()
        ):
            pass

        # 如果密码字段必填,或者有输入内容,则调用父类的默认验证
        else:
            super().validate_passwords(password1_field_name, password2_field_name)

备注:内容来源于stack exchange,提问作者ravioli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:28:10