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

Django中UserCreationForm自定义样式失效问题求助

解决UserCreationForm无法添加'form-control'类的问题

你的代码问题很明确:ProfileForm里的__init__方法缩进错误,它被嵌套在Meta类内部,导致这段给字段添加样式的代码根本不会被执行。而你写的CustomerForm是正确的,因为widgets配置本来就该放在Meta类里,所以能正常生效。

修正后的ProfileForm代码如下:

class ProfileForm(UserCreationForm):
    class Meta:
        model=User
        fields = ('email', 'avatar', 'password1', 'password2')

    # 注意:该__init__方法需和Meta类同级,不能缩进在Meta内部
    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)

        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'

调整缩进后,表单初始化时__init__方法会被正常调用,就能成功给指定字段的widget加上form-control类了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:35:25