Django:在admin multiple select中显示嵌套类别

时间:2010-11-15 09:29:13

标签: django django-admin

我想找到一种获取类别和子类别的方法 显示在管理员中,以多重选择的形式显示。

像:

parent 
----child1 
----child2 
parent2 
----child3 

我是否必须制作自定义字段,或者是否已有解决方案 周围?


修改

模型是:

class Category(models.Model):

    def __unicode__(self):
        return self.name_en

    name = models.CharField(_('name'), max_length=255, null=True)
    slug = models.SlugField(_('slug'), db_index=True, unique=True)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='child')   
    description =  models.TextField(_('description'), null=True)

1 个答案:

答案 0 :(得分:3)

您不需要自定义字段,只需要自定义窗口小部件。这是我做的一个示例小部件。它是未经测试的,所以请将其视为伪代码:)

from django.forms.widgets import SelectMultiple
from django.db.models import *

class Category(Model):
    name = TextField()
    parent = ForeignKey('self', null=True, related_name='children'):

class CategoryTreeWidget(SelectMultiple):
    def render_options(self, choices, selected_choices):
        selected_choices=set([force_unicode(v) for v in selected_choices])
        top_level_cats = Category.objects.filter(parent=None)
        def _render_category_list(cat_list, level=0):
            for category in cat_list:
                self.render_option(selected_choices, category.pk, (("---"*level + " ") if level) + category.name)
                def _render_category_list(category.children, level+1)
        _render_category_list(top_level_cats)

class Article(Model):
    title = TextField()
    body = TextField()
    category = ManyToMany('Category', widget = CategoryTreeWidget)