[Django]-Widget to display categories as tree in Django admin

2👍

Firstly, you haven’t actually defined an order on this model – just a parent. You need something like MPTT which keeps track of the level and the position within that level.

Given that, it’s fairly easy to write a __unicode__ method for the model which displays the number of hyphens equal to the category’s level:

def __unicode__(self):
   return '%s%s' % ('-' * self.level, self.name)

As for the up/down button, you’ll need to write that in Javascript, I expect.

2👍

Here is one widget, based on django-mptt :
http://anentropic.wordpress.com/2009/11/05/more-django-mptt-goodness-filteredselectmultiple-m2m-widget/

looks like what you’re looking for

1👍

There is a django-categories package, which add a select box with all category to your admin site to manage categories.

0👍

It’s very simple

All you have to do in your view is get all objects:

categories = Category.objects.all()

Then in your template :

{% for category in categories %}
  <li>- {{category.name}} </li>
  {% for child in category.children.all %}
     <ul>* {{child.nom}} </ul>
  {% endfor %}
 </li>          
{% endfor %}

0👍

Generating the desired tree like structure requires "Modified Preorder Tree Traversal" of the tabular data. A custom implementation will be fairly complex.

You can use existing package called Django MPTT to simplify the hierarchical tree generation based on your Category model.

With it you can achieve following:

  • get descendants of a node
  • get ancestors of a node
  • get all nodes at a given level
  • get leaf nodes

Leave a comment