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
----child2
parent2
----child3
Do I have to m开发者_如何转开发ake a custom field or is there already a solution around?
Edit
the model is:
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)
精彩评论