在Django中分组复选框选择多个选项 [英] Grouping CheckboxSelectMultiple Options in Django
问题描述
在我的Django应用程序中,我有以下模型:
In my Django App I have the following model:
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的管理界面中尝试完成的是使用小部件CheckboxSelectMultiple渲染类别,但以类别分组通过 SuperCategory ,如下所示:
What I'm trying to accomplish in Django's Admin Interface is the rendering of Category using widget CheckboxSelectMultiple but with Category somehow grouped by SuperCategory, like this:
类别:
体育:<超级类别的项目
[]足球< - 类别项目
[]棒球< - 类别的项目
[] ...
Sports: <- Item of SuperCategory
[ ] Soccer <- Item of Category
[ ] Baseball <- Item of Category
[ ] ...
政治:< - 另一个项目超级类别
[]拉丁美洲
[]北美
[] ...
Politics: <- Another item of SuperCategory
[ ] Latin America
[ ] North america
[ ] ...
有没有人有一个很好的建议如何做到这一点?
Does anybody have a nice suggestion on how to do this?
非常感谢。
推荐答案
经过一番努力,这里是我所得到的。
After some struggle, here is what I got.
首先,使ModelAdmin调用ModelForm:
First, make ModelAdmin call a ModelForm:
class OptionAdmin(admin.ModelAdmin):
form = forms.OptionForm
然后,在窗体中,使用自定义小部件来呈现:
Then, in the form, use use a custom widget to render:
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))
不是最优雅的解决方案,但嘿,它的工作。
Not the most elegant solution, but hey, it worked.
这篇关于在Django中分组复选框选择多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!