2011-09-02 26 views
1

我有這樣的:如何在ModelMultipleChoiceField中顯示選項的標籤?

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列,等有什麼建議?

我知道我可以通過一個列表中的所有設施和房屋設施列表,並做一個for循環來比較它。我只是覺得它不夠高雅和低效。

回答

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 
    ) 
相關問題