Django表单widgets参数报错及Meta配置样式不生效问题求助
报错原因及解决办法
第一个报错:TypeError: __init__() got an unexpected keyword argument 'widgets'
原因:表单字段初始化的参数名为单数 widget,widgets 是 ModelForm 中 Meta 类的专属配置键,直接传入字段初始化方法无法识别,因此抛出参数异常。
第二个问题:Meta 类中 widgets 配置不生效
原因:你继承的 AuthenticationForm 是普通 Form 子类,不是 ModelForm,只有 ModelForm 会读取 Meta 类下的 widgets 配置,普通 Form 不会处理该配置,因此你写的类名属性没有渲染到前端标签上。
两种解决办法:
- 方法1:直接在字段定义时通过
widget参数指定样式,写法如下:
class LoginForm(AuthenticationForm): username = UsernameField( label='username', widget=forms.TextInput(attrs={'autofocus':True, 'class':'form-control'}) ) password = forms.CharField( label='password', strip=False, widget=forms.PasswordInput(attrs={'autocomplete':'current-password', 'class':'form-control'}) )
- 方法2:重写表单的
__init__方法批量更新字段属性:
class LoginForm(AuthenticationForm): username = UsernameField(label='username') password = forms.CharField(label='password', strip=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'autofocus':True, 'class':'form-control'}) self.fields['password'].widget.attrs.update({'autocomplete':'current-password', 'class':'form-control'})
修改后无需调整模板代码,重新运行服务即可看到 form-control 类生效,Bootstrap 样式正常渲染。
内容的提问来源于stack exchange,提问作者Abu RayhaN
相关产品推荐
相关产品推荐

