【问题标题】:Django - Add css class to input field in adminDjango - 将 css 类添加到管理员的输入字段
【发布时间】:2014-02-20 15:14:37
【问题描述】:

我有以下型号:

class InfoBox(models.Model):
    type = models.ForeignKey(InfoBoxType)
    content = models.TextField()
    product = models.ForeignKey(Product)

我想为我的外键添加一个 CSS 类。我尝试了以下方法:

forms.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'

我认为这很容易做到,那么我做错了什么......?

【问题讨论】:

    标签: python css django class


    【解决方案1】:

    试试:

    widgets = {
        'type': Select(attrs={'class': 'hej'}),
    }
    

    这是您所在领域的正确小部件。

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

    self.fields['type'].widget.attrs['class'] = 'hej'
    

    在表单的 init 方法中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2018-01-14
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多