使用django form生成複選框表格
阿新 • • 發佈:2019-02-02
轉自:http://www.zhimaq.com/questions/1690/django-form-checkbox
from django import forms ACTIVITY_STYLE = (("a", "1"), ("b", "2"), ("c", "3")) class HobbiesForm(forms.Form): hobbies = forms.MultipleChoiceField(label=u'活動型別', choices=ACTIVITY_STYLE, widget=forms.CheckboxSelectMultiple()) print HobbiesForm(data={"hobbies": ["a", "b", "c"]}).as_p() print HobbiesForm(data={"hobbies": ["b", "c"]}).as_p()
可以在python manage.py shell啟動的命令列裡,輸入上面程式碼,得到下面結果:
u'<p><label for="id_hobbies_0">\u6d3b\u52a8\u7c7b\u578b:</label> <ul id="id_hobbies">\n<li><label for="id_hobbies_0"><input checked="checked" id="id_hobbies_0" name="hobbies" type="checkbox" value="a" /> 1</label></li>\n<li><label for="id_hobbies_1"><input checked="checked" id="id_hobbies_1" name="hobbies" type="checkbox" value="b" /> 2</label></li>\n<li><label for="id_hobbies_2"><input checked="checked" id="id_hobbies_2" name="hobbies" type="checkbox" value="c" /> 3</label></li>\n</ul></p>'
u'<p><label for="id_hobbies_0">\u6d3b\u52a8\u7c7b\u578b:</label> <ul id="id_hobbies">\n<li><label for="id_hobbies_0"><input id="id_hobbies_0" name="hobbies" type="checkbox" value="a" /> 1</label></li>\n<li><label for="id_hobbies_1"><input checked="checked" id="id_hobbies_1" name="hobbies" type="checkbox" value="b" /> 2</label></li>\n<li><label for="id_hobbies_2"><input checked="checked" id="id_hobbies_2" name="hobbies" type="checkbox" value="c" /> 3</label></li>\n</ul></p>'
遇到問題:相同過cleaned_data()函式獲得form選中的選項,報錯說沒喲cleaned_data屬性,後面發現要先呼叫is_valid()函式才能呼叫cleaned_data()獲得資料。