![](/img/trans.png)
[英]django render initial values in form with ModelMultipleChoiceField and CheckboxSelectMultiple() widget
[英]django modelmultiplechoicefield and widget checkboxselectmultiple
我想要一些類似管理界面的東西。
這是表單的代碼:
class NewRoleFrom(forms.Form):
role = forms.ModelMultipleChoiceField(
queryset=Role.objects.all(),
widget=forms.CheckboxSelectMultiple
)
所以,它很簡單,我有角色標簽(角色:)然后用一個復選框呈現數據庫中的每個角色。 就像我可以找回用戶選擇的所有角色對象。 但是在每一行的開頭我都有一顆子彈,我怎么能把它刪除呢? 那么是否可以在admin.py
定義list_display
時添加其他屬性?
在您的表單模板中迭代角色
{% for role in form.role %}
<div class="checkbox">
{{ role }}
</div>
{% endfor %}
然后用css搞定。
以下是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標記中添加一個類,然后使用此處詳述的解決方案添加您自己的css。
我將使用自定義類覆蓋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;'})
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.