我有这个:
class HouseForm(forms.ModelForm):
amenities = ModelMultipleChoiceField(
queryset=Amenity.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required=False
)
有没有办法构建自己的复选框列表?而不是无序列表中的默认值?
这是我希望实现的目标:
<select>
{% for a in house_form.amenities %}
<option value="{{ a.value }}" {% if a.checked %}selected="selected"{% endif %}>
{{ a.option_name }}</option>
{% endfor %}
</select>
我希望能够自定义列表,分成3列等等。有什么建议吗?
我知道我可以通过列表中的所有设施和房屋设施清单,并进行循环比较。我发现它不优雅且效率低下。
答案 0 :(得分:0)
子类forms.CheckboxSelectMultiple(render()方法?)为您提供所需的输出。
class TabularSelectMultiple(SelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<table>','<tr><th></th><th>Label</th></tr>']
# Normalize to strings
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
label_for = u' for="%s"' % final_attrs['id']
else:
label_for = u''
cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values).render(name, option_value)
option_value = force_unicode(option_value)
option_label = conditional_escape(force_unicode(option_label))
output.append(u'<tr><td>%s</td><td><label%s> %s</label></td></tr>' % (cb, label_for, option_label))
output.append(u'</table>')
return mark_safe(u'\n'.join(output))
class HouseForm(forms.ModelForm):
amenities = ModelMultipleChoiceField(
queryset=Amenity.objects.all(),
widget=TabularSelectMultiple(),
required=False
)