2

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...?

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.