Search code examples
pythondjangomptt

django-mptt nested dropdown in standard ModelAdmin?


I'm using django-mptt for a Category model, which is a foreign key to a Project model:

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Category(MPTTModel):
    name = models.CharField(max_length=255)
    parent = TreeForeignKeyY('self',
            null=True, 
            blank=True, 
            related_name='children'
            )

class Project(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey('Category')

It's easy to set up the Category admin using MPTTModelAdmin, complete with a nice nested dropdown for picking parent category:

from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from myapp.models import Category, Project

admin.site.register(Category, MPTTModelAdmin)

Now I'd like to include a nice nested Category dropdown in my Project admin, but the standard admin.ModelAdmin does not include this functionality and subclassing MPTTModelAdmin doesn't seem to work:

Project has no field named 'parent'

Is it possible to mimic the nested dropdown in a non-MPTT admin tool?


Solution

  • You can still use TreeForeignKey on a non-MPTTModel, assuming that the linked model is an MPTTModel, i.e.:

    class Project(models.Model):
        name = models.CharField(max_length=255)
        category = TreeForeignKey('Category')
    

    Alternatively, you can make the field an instance of mptt.forms.TreeNodeChoiceField or mptt.forms.TreeNodeMultipleChoiceField on your form.