Django MPTT

0.18.0 · maintenance · verified Sat Apr 11

django-mptt is a reusable Django application that simplifies the implementation of Modified Preorder Tree Traversal (MPTT) for hierarchical data in Django models. It provides tools for managing and working with trees of model instances, including automatic updates for tree structures, custom managers, and admin classes. The current version is 0.18.0, and while it continues to receive compatibility updates for newer Django and Python versions, the project maintainers note that the project is "currently unmaintained" in terms of active feature development, suggesting users consider alternatives for new projects.

Warnings

Install

Imports

Quickstart

To get started with django-mptt, add 'mptt' to your `INSTALLED_APPS`. Define your hierarchical model by inheriting from `mptt.models.MPTTModel` and including a `TreeForeignKey` field pointing to 'self' for the parent relationship. Optionally, specify `MPTTMeta.order_insertion_by` for natural ordering. For an interactive admin interface, register your model with `mptt.admin.DraggableMPTTAdmin`.

# settings.py
INSTALLED_APPS = [
    # ...
    'mptt',
    'myapp', # your app name
    # ...
]

# myapp/models.py
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE,
                            null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

    def __str__(self):
        return self.name

# myapp/admin.py
from django.contrib import admin
from mptt.admin import DraggableMPTTAdmin
from .models import Category

@admin.register(Category)
class CategoryAdmin(DraggableMPTTAdmin):
    list_display = ('tree_actions', 'indented_title',)
    list_display_links = ('indented_title',)

    # Optional: to expand the tree by default
    expand_tree_by_default = True

view raw JSON →