Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hierarchical data in admin pages in Django

In a Django project, I have a hierarchical model using MPTT defined like this in models.py:

class Structure(MPTTModel):
    name = models.CharField(max_length=200, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    [...]

I'm using FeinCMS to show this hierarchical data in admin pages. I do it like this in admin.py:

class StructureAdmin(tree_editor.TreeEditor):
    search_fields = ('name',)

[...]

admin.site.register(Structure, StructureAdmin)

In the admin model page, it works perfectly and the hierarchy can be seen: enter image description here

It also works when editing or adding:

enter image description here

I have another model in models.py:

class Track(models.Model):
    initialStructure = models.ForeignKey(Structure , related_name='track_initialStructure')
    finalStructure = models.ForeignKey(Structure, related_name='track_finalStructure')
    [...]

However, when adding a new element of this kind, the hierarchy can not be seen:

enter image description here

I've tried to use tree_editor.TreeEditor for the admin view of Track but it gives a lot of errors because Track is not hierarchical, but some of its ForeignKey's are. How could I show the hierarchy when editing an element of model Track?

Thank you very much.

like image 862
A.Vila Avatar asked Feb 11 '13 20:02

A.Vila


1 Answers

Try changing:

finalStructure = models.ForeignKey(Structure, related_name='track_finalStructure')

to:

finalStructure = TreeForeignKey(Structure, related_name='track_finalStructure')

of course, after importing TreeForeignKey from django-mptt:

from mptt.fields import TreeForeignKey
like image 177
maq Avatar answered Oct 27 '22 19:10

maq