Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initial value in radio button django form

how can I declare initial value of radio button?

form.py

YESNO = (
    ('Yes','Yes'),
    ('No', 'No'),
)
class MyForm(forms.Form):
   like = forms.ChoiceField(widget=forms.RadioSelect, choices=YESNO)

myhtml.html

{{form.like}}

i try to put:

like = forms.ChoiceField(widget=forms.RadioSelect, choices=YESNO, initial={'Yes':'Yes'})

when i run my code, my radio button has not yet selected..

like image 259
gadss Avatar asked Mar 06 '12 06:03

gadss


1 Answers

Yes, this should be done in the view, but the syntax in the accepted answer is incorrect, as it will trigger field validation on all fields before submitting the form. Use instead:

def myviews(request):
  .....
  form = MyForm(initial={'like':'Yes'})
  ...
like image 88
shacker Avatar answered Sep 26 '22 11:09

shacker