I am using a ModelForm and trying to set a css class on a Django forms.RadioSelect widget like
class Meta:
model = models.MyModel
fields = ('rating',)
widgets = {
'rating': forms.RadioSelect(attrs={'class':'star'}),
}
but class='star' does not get rendered in the html.
I also tried using:
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields['rating'].widget.attrs['class'] = 'star'
which also did not work. I tried the same thing with forms.Textarea widget and there I was able to get the css class rendered.
Am I doing anything wrong here or does RadioSelect just no support the class attribute (I want the class name applied to all radio inputs)?
The checkbox and radio widgets do not inherit from Input
like the other widgets.
The class attribute does work for the RadioSelect
, but it is applied to every radio input individually.
For example consider the following form:
from django import forms
class MyForm(forms.Form):
my_field = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'star'}), choices=(('x', 'x'), ('y', 'y'),))
It will output the following html in the template:
<tr><th><label for="id_my_field_0">My field:</label></th>
<td>
<ul>
<li><label for="id_my_field_0"><input value="x" type="radio" class="star" name="my_field" id="id_my_field_0" /> x</label></li>
<li><label for="id_my_field_1"><input value="y" type="radio" class="star" name="my_field" id="id_my_field_1" /> y</label></li>
</ul>
</td>
</tr>
Note that the class is applied to each input
element.