Search code examples
djangodjango-formsdjango-widget

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'})

Solution

  • 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'}