initial value in radio button django form

╄→гoц情女王★ 提交于 2020-01-12 14:16:11

问题


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..


回答1:


i put the initial value direct in my views.py...

def myviews(request):
  .....
  form = MyForm({'like':'Yes'})
  ...



回答2:


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'})
  ...



回答3:


you can check documentation forms field initial.




回答4:


this is the way it works initial='N' which is the first item in the tuple. Choices=(('Y','Yes'), ('N','No') rs_field = forms.ChoiceField(choices=Choices),initial='N', widget=forms.RadioSelect)



来源:https://stackoverflow.com/questions/9578877/initial-value-in-radio-button-django-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!