在Django中对CheckboxSelectMultiple选项进行分组

4 投票
2 回答
2332 浏览
提问于 2025-04-16 13:02

在我的Django应用中,我有一个这样的模型:

class SuperCategory(models.Model):
  name = models.CharField(max_length=100,)
  slug = models.SlugField(unique=True,)

class Category(models.Model):
  name            = models.CharField(max_length=100,)
  slug            = models.SlugField(unique=True,)
  super_category  = models.ForeignKey(SuperCategory)

我想在Django的管理界面中实现的是,使用复选框选择多个选项的方式来显示类别,并且希望类别能够按照超级类别进行分组,像这样:


类别:

体育: <- 超级类别的一个项目
[ ] 足球 <- 类别的一个项目
[ ] 棒球 <- 类别的一个项目
[ ] ...

政治: <- 另一个超级类别的项目
[ ] 拉丁美洲
[ ] 北美
[ ] ...


有没有人有好的建议来实现这个呢?

非常感谢。

2 个回答

0

我遇到的情况有点不同,但我希望我把代码调整得适合提问者的情况。接下来这段代码应该可以在Django 4.2中解决问题:

# Custom UI Component
class GroupedCheckboxSelectMultiple(CheckboxSelectMultiple):
    def render(self, name, value, attrs=None, renderer=None):
        widget_id = f"id_{name}"
        html = ""
        html += f'<div id="{widget_id}" class="grouped-checkbox-select-multiple">'
        # sort since groupby needs sorted data to work "properly"
        sorted_choices = sorted(self.choices, key=lambda choice: choice.super_category or "")
        id_count = 0
        for group, choices in itertools.groupby(
            sorted_choices, lambda choice: choice.super_category
        ):
            html += '<div class="choice-group">'
            html += f'<span class="group-title">{group}</span>'
            for choice in choices:
                identifier = f"{widget_id}_{id_count}"
                html += f"""<div class="choice-wrapper">
                            <input id="{identifier}" name="{name}" type="checkbox" value={choice.name}>"""
                html += f'      <label for="{identifier}">{choice.name}</label>'
                html += "</div>"
                id_count += 1
            html += "</div>"
        html += "</div>"
        return html

然后我在一个表单中这样使用它:

class ProjectDataForm(Form):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        raw_choices = fetch_choices()
        choices = list(map(lambda item: (item.name, item.name), raw_choices))
        self.fields["category"].choices = choices
        self.fields["category"].widget.choices = raw_choices

    category = MultipleChoiceField(widget=GroupedCheckboxSelectMultiple())
5

经过一番努力,我得到了这个结果。

首先,让ModelAdmin调用一个ModelForm:

class OptionAdmin(admin.ModelAdmin):

   form = forms.OptionForm

然后,在表单中,使用一个自定义的控件来渲染:

category = forms.ModelMultipleChoiceField(queryset=models.Category.objects.all(),widget=AdminCategoryBySupercategory)    

最后,就是这个控件:

class AdminCategoryBySupercategory(forms.CheckboxSelectMultiple):

     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])
         supercategories = models.SuperCategory.objects.all()
         for supercategory in supercategories:
             output.append(u'<li>%s</li>'%(supercategory.name))
             output.append(u'<ul>')
             del self.choices
             self.choices = []
             categories = models.Category.objects.filter(super_category=supercategory)
             for category in categories:
                 self.choices.append((category.id,category.name))
             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 = ''
                 cb = forms.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>')
             output.append(u'</li>')
         output.append(u'</ul>')
         return mark_safe(u'\n'.join(output))

这不是最优雅的解决方案,但嘿,它确实有效。

撰写回答