how can I declare initial value of radio button?
如何声明单选按钮的初始值?
form.py
form.py
YESNO = (
('Yes','Yes'),
('No', 'No'),
)
class MyForm(forms.Form):
like = forms.ChoiceField(widget=forms.RadioSelect, choices=YESNO)
myhtml.html
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..
当我运行我的代码时,我的单选按钮尚未选中..
3 个解决方案
#1
3
i put the initial value direct in my views.py
...
我把初始值直接放在我的views.py中......
def myviews(request):
.....
form = MyForm({'like':'Yes'})
...
#3
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'})
...
#1
3
i put the initial value direct in my views.py
...
我把初始值直接放在我的views.py中......
def myviews(request):
.....
form = MyForm({'like':'Yes'})
...
#2
#3
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'})
...