Django: display nested categories in admin multiple select

前端 未结 1 1147
失恋的感觉
失恋的感觉 2021-02-06 16:04

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

Like:

parent 
----child1 
----         


        
1条回答
  •  野的像风
    2021-02-06 16:58

    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)
    

    0 讨论(0)
提交回复
热议问题