jul
jul

Reputation: 37474

Widget to display categories as tree in Django admin

is there any existing code to display the list of some Category object in the admin of a Django site? Ideally I'd like some tree representation like

cat_1

----cat_1_1

----cat_1_2

cat_2

cat_3

----cat_3_1

----cat_3_2

----cat_3_3

with up/down button to change the order.

class Category(models.Model):

    parent = models.ForeignKey('self', null=True, related_name='children')
    name = models.CharField(max_length=100)

Upvotes: 3

Views: 8706

Answers (5)

Rahul Chauhan
Rahul Chauhan

Reputation: 61

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

Upvotes: 0

Armance
Armance

Reputation: 5390

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 %}

Upvotes: 0

Lukasz Koziara
Lukasz Koziara

Reputation: 4320

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

Upvotes: 1

Dominique Guardiola
Dominique Guardiola

Reputation: 3431

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

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599698

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.

Upvotes: 2

Related Questions