开发者

How to display the options' label in ModelMultipleChoiceField?

I have this:

class HouseForm(forms.ModelForm):
    amenities = ModelMultipleChoiceField(
        queryset=Amenity.objects.all(),
        widget=forms.CheckboxSelectMultiple(),
        required=False
    )

Is there a way I can construct my own list of checkboxes? Instead of the default in unordered list?

Here's what I hope to achieve:

<select>
{% for a in house_form.amenities %}
  <option value="{{ a.value }}" {% if a.checked %}selected="selected"{% endif %}> 
  {{ a.option_name }}</option>
{% endfor %}
</select>

I hope to be able to customize the list, break into 3 columns, etc. Any suggestions?

I know I can passed in a list of all the amenities and a list of amenities in the house and do a for loop to compare it. I just find it not-elegant and inefficient. 开发者_Python百科


subclass forms.CheckboxSelectMultiple (render() method?) to give you the required output.

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
    )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜