我正在为我的表单 Post
使用模型表单,并且使用引导启动代码作为我的 base.html
但因为我使用 { % csrf_token %} {{form.as_p}}
在我的 add_blog
页面上,bootstrap 不起作用,因此它需要 class='form-control'
,我已经设法在除选择输入之外的所有字段上执行此操作,如果我在小部件中包含我的作者(choicefield),我会收到 TypeError: init() got an Unexpected keywords argument '属性'
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ("title", "title_tag", "author", "body")
widget = forms.Select(attrs={"class": "form-control"})
widgets = {
'title': TextInput(attrs={'class': 'form-control'}),
'title_tag': TextInput(attrs={'class': 'form-control'}),
'body': Textarea(attrs={'class': 'form-control'}),
'author': ChoiceField(attrs={'class': 'form-control'})
}
最佳答案
一个ChoiceField
[Django-doc]是表单字段,而不是表单小部件。 ChoiceField
的默认小部件是 Select
[Django-doc] 。因此,您可以指定使用此小部件:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'title_tag', 'author', 'body')
widgets = {
'title': TextInput(attrs={'class': 'form-control'}),
'title_tag': TextInput(attrs={'class': 'form-control'}),
'body': Textarea(attrs={'class': 'form-control'}),
'author': <strong>Select(</strong>attrs={'class': 'form-control'}<strong>)</strong>
}
关于python - 模型表单中 ChoiceField 的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68809218/