Django forms + list of checkboxes + list of radiobuttons

牧云@^-^@ 提交于 2019-12-11 05:33:35

问题


Do You know how to change this list of checkboxes code:

<p>How did you reach this site? <select name="howreach">
<option value="0" selected="selected">Choose one...</option>
<option value="1">Typed the URL directly</option>
<option value="2">Site is bookmarked</option>
<option value="3">A search engine</option>
<option value="4">A link from another site</option>
<option value="5">From a book</option>
<option value="6">Other</option>
</select></p>

to the django forms?

And how to change this to the list of radio buttons in Django forms?:

Poor <input type="radio" name="rating" value="1" /> 1 
<input type="radio" name="rating" value="2" /> 2 
<input type="radio" name="rating" value="3" /> 3 
<input type="radio" name="rating" value="4" /> 4 
<input type="radio" name="rating" value="5" /> 5 Excellent</p>

回答1:


In your python code:

class SiteReach(forms.Form):
    howreach = forms.ChoiceField(label = "How did you reach this site?",
                                 choices = HOWREACH_CHOICES, 
                                 widget = forms.widgets.CheckboxInput())

You'll have to initialize HOWREACH_CHOICES on your own; it's a list of tuples, (option value, option string).

You render radio buttons in the same way:

class Rating(forms.Form):
    rating = forms.ChoiceField(choices = range(1,6),
                               widget = forms.widgets.RadioSelect())

Read the documentation on Widgets; there's a whole universe of utility in there.



来源:https://stackoverflow.com/questions/4381300/django-forms-list-of-checkboxes-list-of-radiobuttons

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