JOSEFtw
JOSEFtw

Reputation: 10091

Django - Add css class to input field in admin

I have the following model:

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

I want to add a css class to my foreignkey. I've tried the following:

forms.py

class InfoBoxForm(ModelForm):
    class Meta:
        model = InfoBox
        widgets = {
            'type': ChoiceField(attrs={'class': 'hej'}),
        }

I've also tried this but with the same result...

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

But im only getting this:

__init__() got an unexpected keyword argument 'attrs'

Im thinking that this would be pretty easy to do, so what am I doing wrong...?

Upvotes: 2

Views: 4609

Answers (1)

Alvaro
Alvaro

Reputation: 12037

Try:

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

This is the correct widget for your field.

If you don't want to overwrite the widget, you can use:

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

in the form's init method

Upvotes: 7

Related Questions