Django:在管理员多选中显示嵌套类别 [英] Django: display nested categories in admin multiple select

查看:136
本文介绍了Django:在管理员多选中显示嵌套类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to find a way to get categories and subcategories displayed in the admin, in the form of a multiple select.

喜欢:

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

我必须制作一个自定义字段,还是有一个解决方案

Do I have to make a custom field or is there already a solution around?

模型是:

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)


推荐答案

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

You don't need a custom field, just a custom widget. Here is an example widget i cooked up. it's untested, so treat it like pseudo-code :)

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)

这篇关于Django:在管理员多选中显示嵌套类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆