分组复选框在Djang中选择多个选项

2024-04-25 06:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的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的管理界面中实现的是使用widget CheckboxSelectMultiple,但使用类别以某种方式按超级类别分组的方式呈现类别,如下所示:


Category:

Sports: <- Item of SuperCategory
[ ] Soccer <- Item of Category
[ ] Baseball <- Item of Category
[ ] ...

Politics: <- Another item of SuperCategory
[ ] Latin America
[ ] North america
[ ] ...


有人有什么好建议吗?在

非常感谢。在


Tags: ofdjangonamemodelmodelsitem类别length
1条回答
网友
1楼 · 发布于 2024-04-25 06:52:05

经过一番挣扎,这是我得到的。在

首先,使ModelAdmin调用ModelForm:

class OptionAdmin(admin.ModelAdmin):

   form = forms.OptionForm

然后,在表单中,使用自定义小部件呈现:

^{pr2}$

最后,小部件:

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

不是最优雅的解决方案,但是嘿,它奏效了。在

相关问题 更多 >