Search code examples
djangodjango-templatesdjango-widget-tweaks

how to add css class to radio button in django template


I am trying to do the following with django widget tweaks:

{{ form.gender.0.tag|attr:"class:radio_1" }}

I get the error:

'SafeText' object has no attribute 'as_widget'

What am I doing wrong?


Solution

  • Initialize your RadioButton like this:

    CHOICES=[('option1','option1'),
             ('option2','option2')]
    
    radio = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(attrs={'class': 'radio_1'}))
    

    and the generated HTML-Code will look like this:

    <input type="radio" class="radio_1" ... />