Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Widget to display categories as tree in Django admin

Tags:

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)
like image 706
jul Avatar asked Dec 21 '25 07:12

jul


2 Answers

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.

like image 172
Daniel Roseman Avatar answered Dec 24 '25 00:12

Daniel Roseman


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

like image 40
Dominique Guardiola Avatar answered Dec 24 '25 00:12

Dominique Guardiola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!