Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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'})
like image 631
Michael Smith Avatar asked Nov 04 '14 01:11

Michael Smith


1 Answers

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)
like image 199
gseva Avatar answered Oct 06 '22 00:10

gseva