initial value in radio button django form

后端 未结 4 1124
暗喜
暗喜 2021-02-19 19:28

how can I declare initial value of radio button?

form.py

YESNO = (
    (\'Yes\',\'Yes\'),
    (\'No\', \'No\'),
)
class MyForm(forms.Form):
   like = for         


        
相关标签:
4条回答
  • 2021-02-19 19:33

    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)

    0 讨论(0)
  • 2021-02-19 19:47

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

    def myviews(request):
      .....
      form = MyForm({'like':'Yes'})
      ...
    
    0 讨论(0)
  • 2021-02-19 19:54

    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'})
      ...
    
    0 讨论(0)
  • 2021-02-19 19:54

    you can check documentation forms field initial.

    0 讨论(0)
提交回复
热议问题