Django - 将css类添加到admin中的输入字段

JOS*_*Ftw 1 css python django class

我有以下型号:

class InfoBox(models.Model):
    type = models.ForeignKey(InfoBoxType)
    content = models.TextField()
    product = models.ForeignKey(Product)
Run Code Online (Sandbox Code Playgroud)

我想在我的外键中添加一个css类.我尝试过以下方法:

forms.py

class InfoBoxForm(ModelForm):
    class Meta:
        model = InfoBox
        widgets = {
            'type': ChoiceField(attrs={'class': 'hej'}),
        }
Run Code Online (Sandbox Code Playgroud)

我也试过了,但结果相同......

class InfoBoxForm(forms.Form):

    type = forms.ChoiceField(
            widget=forms.ChoiceField(attrs={'class':'special'}))
Run Code Online (Sandbox Code Playgroud)

admin.py

class InfoBoxInline(admin.StackedInline):
    model = InfoBox
    extra = 0
    form = InfoBoxForm
Run Code Online (Sandbox Code Playgroud)

但我只是得到这个:

__init__() got an unexpected keyword argument 'attrs'
Run Code Online (Sandbox Code Playgroud)

我觉得这样做很容易,所以我做错了什么......?

Alv*_*aro 6

尝试:

widgets = {
    'type': Select(attrs={'class': 'hej'}),
}
Run Code Online (Sandbox Code Playgroud)

这是您的领域的正确小部件.

如果您不想覆盖窗口小部件,可以使用:

self.fields['type'].widget.attrs['class'] = 'hej'
Run Code Online (Sandbox Code Playgroud)

在表单的init方法中