使用django form生成复选框表格

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值