转自: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()获得数据。