Michael Smith
Michael Smith

Reputation: 3447

How do I 'check' a radio button value using django RadioSelect widget

In HTML you can easily do this by using the word 'checked' next to a radio button input field.

How do you do this in django using ModelForm?

I have 2 choices for my radio button code 'Regular Service' and 'Premium Service'. I would like 'Regular Service' to automatically be checked.

Here are the relevant parts of my forms.py

CHOICES = (
    (1,'Regular Service'),
    (0,'Premium Service')
)

class ServiceForm(forms.ModelForm):
     regular_service = forms.ChoiceField(required = True, choices = CHOICES, widget=forms.RadioSelect(attrs={'class' : 'Radio'}), initial={'regular_service':'Regular Service'})

Upvotes: 6

Views: 7534

Answers (1)

gseva
gseva

Reputation: 373

You should set initial to 1, which is the key of the choice you want to be checked.

class ServiceForm(forms.ModelForm):
    regular_service = forms.ChoiceField(required = True, choices = CHOICES, widget=forms.RadioSelect(attrs={'class' : 'Radio'}), initial=1)

Upvotes: 13

Related Questions