我有以下模型:
class InfoBox(models.Model):
type = models.ForeignKey(InfoBoxType)
content = models.TextField()
product = models.ForeignKey(Product)
我想为我的外键添加一个 css 类。我尝试了以下方法:
表单.py
class InfoBoxForm(ModelForm):
class Meta:
model = InfoBox
widgets = {
'type': ChoiceField(attrs={'class': 'hej'}),
}
我也试过这个,但结果相同......
class InfoBoxForm(forms.Form):
type = forms.ChoiceField(
widget=forms.ChoiceField(attrs={'class':'special'}))
admin.py
class InfoBoxInline(admin.StackedInline):
model = InfoBox
extra = 0
form = InfoBoxForm
但我只得到这个:
__init__() got an unexpected keyword argument 'attrs'
我认为这很容易做到,所以我做错了什么......?
请您参考如下方法:
尝试:
widgets = {
'type': Select(attrs={'class': 'hej'}),
}
这是适合您领域的小部件。
如果你不想覆盖小部件,你可以使用:
self.fields['type'].widget.attrs['class'] = 'hej'
在表单的初始化方法中
