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
----
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)