【发布时间】:2013-09-06 16:18:21
【问题描述】:
forms.py
class TypeSelectionForm(forms.Form):
checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), label="", required=False)
def __init__(self, type_id, *args, **kwargs):
super(TypeSelectionForm, self).__init__(*args, **kwargs)
_type_checkbox = self.fields['checkbox_field']
MY_CHOICES=((type.id, type.title) for type in type)
_type_checkbox.choices = MY_CHOICES
initial_val = []
type_selection = Types.objects.filter(parent_type_id=type_id,is_active=True)
for type_selection in type_selection:
initial_val.append(type_selection.id)
_type_checkbox.initial = initial_val
views.py
def types(method):
""""""""""""
types = TypeSelectionForm(type_id)
return render(request,'types.html',{'types':types})
在模板中,我正在渲染这样的字段,
types.html
{% for field in types.checkbox_field %}
<div class="deletelist">
{{field}}<br />
</div>
{% endfor %}
它正在生成这样的html,
<ul>
<li><label for="id_checkbox_field_0"><input checked="checked" type="checkbox" name="checkbox_field" value="597" id="id_checkbox_field_0" /> comp lab</label></li>
<li><label for="id_checkbox_field_1"><input checked="checked" type="checkbox" name="checkbox_field" value="598" id="id_checkbox_field_1" /> phy lab</label></li>
<li><label for="id_checkbox_field_2"><input checked="checked" type="checkbox" name="checkbox_field" value="599" id="id_checkbox_field_2" /> chem lab</label></li>
</ul>
我想用<div class="class-name"> 替换<ul> 和<li> 标签
需要帮助。
【问题讨论】:
-
MY_CHOICES=((type.id, type.title) for type in type),这将显示类型对象的 id 和标题。在该类上添加一个 unicode 方法来回答您希望显示的内容,然后只需使用 MY_CHOICES=(type for type in type),这在编程上看起来很奇怪。另外,你为什么不使用 ModelMultipleChoiceField?
-
@professorDante 在模板中显示正确,我手动添加了一个复选框字段,当尝试保存它时它没有被保存所以检查并且在视图中它给出了这个错误“类型对象不可迭代“。但是根据 django doc 1.4,如果我们迭代 form.fieldname,它应该显示带有值的复选框以及添加的 div。现在我使用的是 django 1.4.1,那么为什么我的应用程序不支持它
标签: python django django-models django-forms django-templates