2013-04-08 36 views
2

我想有類似管理界面的東西。django modelmultiplechoicefield和小部件checkboxselectmultiple

這裏是表單代碼:

class NewRoleFrom(forms.Form): 
    role = forms.ModelMultipleChoiceField(
     queryset=Role.objects.all(), 
     widget=forms.CheckboxSelectMultiple 
    ) 

所以,這很簡單,我有角色標籤(角色:)然後在數據庫中每個角色呈現一個複選框。像這樣我可以找回用戶選擇的所有角色對象。 但是在每一行的開頭我有一個子彈,我該如何刪除它? 那麼是否有可能在每個其他屬性上添加屬性,就像我們在admin.py中定義list_display一樣?

回答

0

這裏是從django.forms.widgets模塊插件的源:

class CheckboxSelectMultiple(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'<ul>'] 
     # 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 an ID attribute was given, add a numeric index as a suffix, 
      # so that the checkboxes don't all have the same ID attribute. 
      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 = '' 

      cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values) 
      option_value = force_unicode(option_value) 
      rendered_cb = cb.render(name, option_value) 
      option_label = conditional_escape(force_unicode(option_label)) 
      output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label)) 
     output.append(u'</ul>') 
     return mark_safe(u'\n'.join(output)) 

    def id_for_label(self, id_): 
     # See the comment for RadioSelect.id_for_label() 
     if id_: 
      id_ += '_0' 
     return id_ 

你可以看到子彈是由於Django的CSS的名單。因此,要刪除它們,請考慮創建一個從CheckboxSelectMultiple繼承的新wudget,並在「ul」html標記中添加一個類,然後將詳細的here添加到您自己的css中。

1

在您的表單模板只是遍歷角色

form.html

{% for role in form.role %} 
    <div class="checkbox"> 
     {{ role }} 
    </div> 
{% endfor %} 

然後用CSS靚起來。

0

我會用自定義類重寫CheckboxSelectMultiple類,並直接在渲染輸出中插入樣式更改。見下面

class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple): 
    def __init__(self, attrs=None): 
     super(CustomCheckboxSelectMultiple, self).__init__(attrs) 

    def render(self, name, value, attrs=None, choices=()): 
     output = super(CustomCheckboxSelectMultiple, self).render(name, value, attrs, choices) 

     style = self.attrs.get('style', None) 
     if style: 
      output = output.replace("<ul", format_html('<ul style="{0}"', style)) 

     return mark_safe(output) 

然後在你的表單代碼:

class NewRoleFrom(forms.Form): 
    role = forms.ModelMultipleChoiceField(
     queryset=Role.objects.all(), 
     widget=CustomCheckboxSelectMultiple(attrs={'style': 'list-style: none; margin: 0;'}) 
    ) 
相關問題