django-treenode
raw JSON → 0.24.0 verified Fri May 01 auth: no python
Probably the best abstract model/admin for your tree based stuff. Provides a Django model and admin mixin for managing tree structures using Materialized Path. Current version 0.24.0 supports Django 3.2–6.0 and Python 3.7–3.14. Released regularly, with recent versions adding Django 6.0 and Python 3.14 support.
pip install django-treenode Common errors
error django.core.exceptions.ImproperlyConfigured: The model 'myapp.Category' is not a TreeNodeModel. ↓
cause The model does not inherit from TreeNodeModel or the ForeignKey is not named 'tn_parent'.
fix
Ensure your model inherits from TreeNodeModel and has a ForeignKey called 'tn_parent'.
error RuntimeError: maximum recursion depth exceeded ↓
cause Circular parent assignment detected (or a bug in versions <0.23.3).
fix
Upgrade to >=0.23.3, or check your code for circular parent assignments.
error AttributeError: 'Category' object has no attribute 'tn_order' ↓
cause The model fields are not created because the model was not properly set up as a TreeNodeModel.
fix
Ensure the model inherits from TreeNodeModel and that you have run migrations after adding the inheritance.
Warnings
gotcha You must define a ForeignKey named 'tn_parent' on your model. Using a different name will not be recognized. ↓
fix Add a ForeignKey to self with related_name='children' and null=True, blank=True, and name it exactly 'tn_parent'.
gotcha Cache must be configured for tree operations to work correctly. If not, tree methods may silently fail or log warnings. ↓
fix Ensure Django's cache framework is configured (e.g., CACHES setting). If you don't need caching, set a dummy cache.
gotcha Circular references are now detected (since 0.23.3) but can still cause infinite recursion in older versions. Upgrade if you see recursion errors. ↓
fix Upgrade to 0.23.3 or later.
gotcha In multi-database setups, write operations may not use the correct database. Fixed in 0.20.2. ↓
fix Upgrade to 0.20.2 or later.
Imports
- TreeNodeModel wrong
from treenode import TreeNodecorrectfrom treenode.models import TreeNodeModel
Quickstart
from django.db import models
from treenode.models import TreeNodeModel
class Category(TreeNodeModel):
tn_parent = models.ForeignKey(
'self',
on_delete=models.CASCADE,
null=True,
blank=True,
related_name='children'
)
name = models.CharField(max_length=255)
def __str__(self):
return self.name