YPCrumble
YPCrumble

Reputation: 28682

Can I change a form widget class without redefining it explicitly in Django?

I'm trying to change the class of a Django form field. My form looks like:

class MyForm(forms.Form):
    my_field = forms.ChoiceField(choices=myChoices)

Why is it that it only works to change the class of the Select field explicitly? I want the default Select widget, is there a way to change its attrs without redefining it? This works:

class MyForm(forms.Form):
    myfield = forms.ChoiceField(choices=myChoices, widget=forms.Select(attrs={'class': 'myclass'}))

But this, which seems logical and simpler, raises TypeError: __init__() got an unexpected keyword argument 'attrs'?

class MyForm(forms.Form):
    myfield = forms.ChoiceField(choices=myChoices, attrs={'class': 'myclass'})

Upvotes: 1

Views: 68

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

It's more code, but if you really don't want to define the widget type class, you can do:

class MyForm(forms.Form):
    myfield = forms.ChoiceField(choices=myChoices)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs={'class': 'myclass'}

Upvotes: 1

Related Questions