Skip to main content

django-polymorphic-tree

https://github.com/django-polymorphic/django-polymorphic-tree/actions/workflows/tests.yaml/badge.svg?branch=master https://img.shields.io/pypi/v/django-polymorphic-tree.svg https://img.shields.io/pypi/l/django-polymorphic-tree.svg https://img.shields.io/codecov/c/github/django-polymorphic/django-polymorphic-tree/master.svg

This package combines django-mptt with django-polymorphic. You can write Django models that form a tree structure where each node can be a different model type.

Example uses:

  • Build a tree of organisation and company types (e.g. Partner, Reseller, Group and Customer)

  • Build a tree of a root node, category nodes, leaf nodes, each with custom fields.

  • Build a todo list of projects, categories and items.

  • Build a book of chapters, sections, and pages.

Origin

This code was created in django-fluent-pages, and extracted to become a separate package. This was done during contract work at Leukeleu (known for django-fiber).

Installation

First install the module, preferably in a virtual environment:

pip install django-polymorphic-tree

Or install the current repository:

pip install -e git+https://github.com/django-polymorphic/django-polymorphic-tree.git#egg=django-polymorphic-tree

The main dependencies are django-mptt and django-polymorphic, which will be automatically installed.

Configuration

Next, create a project which uses the application:

cd ..
django-admin.py startproject demo

Add the following to settings.py:

INSTALLED_APPS += (
    'polymorphic_tree',
    'polymorphic',
    'mptt',
)

Usage

The main feature of this module is creating a tree of custom node types. It boils down to creating a application with 2 files:

The models.py file should define the custom node type, and any fields it has:

from django.db import models
from django.utils.translation import gettext_lazy as _
from polymorphic_tree.models import PolymorphicMPTTModel, PolymorphicTreeForeignKey


# A base model for the tree:

class BaseTreeNode(PolymorphicMPTTModel):
    parent = PolymorphicTreeForeignKey('self', blank=True, null=True, related_name='children', verbose_name=_('parent'))
    title = models.CharField(_("Title"), max_length=200)

    class Meta(PolymorphicMPTTModel.Meta):
        verbose_name = _("Tree node")
        verbose_name_plural = _("Tree nodes")


# Create 3 derived models for the tree nodes:

class CategoryNode(BaseTreeNode):
    opening_title = models.CharField(_("Opening title"), max_length=200)
    opening_image = models.ImageField(_("Opening image"), upload_to='images')

    class Meta:
        verbose_name = _("Category node")
        verbose_name_plural = _("Category nodes")


class TextNode(BaseTreeNode):
    extra_text = models.TextField()

    # Extra settings:
    can_have_children = False

    class Meta:
        verbose_name = _("Text node")
        verbose_name_plural = _("Text nodes")


class ImageNode(BaseTreeNode):
    image = models.ImageField(_("Image"), upload_to='images')

    class Meta:
        verbose_name = _("Image node")
        verbose_name_plural = _("Image nodes")

The admin.py file should define the admin, both for the child nodes and parent:

from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from polymorphic_tree.admin import PolymorphicMPTTParentModelAdmin, PolymorphicMPTTChildModelAdmin
from . import models


# The common admin functionality for all derived models:

class BaseChildAdmin(PolymorphicMPTTChildModelAdmin):
    GENERAL_FIELDSET = (None, {
        'fields': ('parent', 'title'),
    })

    base_model = models.BaseTreeNode
    base_fieldsets = (
        GENERAL_FIELDSET,
    )


# Optionally some custom admin code

class TextNodeAdmin(BaseChildAdmin):
    pass


# Create the parent admin that combines it all:

class TreeNodeParentAdmin(PolymorphicMPTTParentModelAdmin):
    base_model = models.BaseTreeNode
    child_models = (
        models.CategoryNode,
        models.TextNode,  # custom admin allows custom edit/delete view.
        models.ImageNode,
    )

    list_display = ('title', 'actions_column',)

    class Media:
        css = {
            'all': ('admin/treenode/admin.css',)
        }


admin.site.register(models.CategoryNode, BaseChildAdmin)
admin.site.register(models.TextNode, TextNodeAdmin)
admin.site.register(models.ImageNode, BaseChildAdmin)
admin.site.register(models.BaseTreeNode, TreeNodeParentAdmin)

The child_models attribute defines which admin interface is loaded for the edit and delete page. The list view is still rendered by the parent admin.

Tests

To run the included test suite, execute:

./runtests.py

To test support for multiple Python and Django versions, you need to follow steps below:

  • install project requirements in virtual environment

  • install python 2.7, 3.4, 3.5, 3.6 python versions through pyenv (See pyenv (Linux) or Homebrew (Mac OS X).)

  • create .python-version file and add full list of installed versions with which project have to be tested, example:

    2.6.9
    2.7.13
    3.4.5
    3.5.2
    3.6.0
  • run tox from the repository root:

    pip install tox
    tox

Python 2.7, 3.4, 3.5 and 3.6 and django 1.8, 1.10 and 1.11 are the currently supported versions.

Todo

  • Sphinx Documentation

Contributing

This module is designed to be generic. In case there is anything you didn’t like about it, or think it’s not flexible enough, please let us know. We’d love to improve it!

If you have any other valuable contribution, suggestion or idea, please let us know as well because we will look into it. Pull requests are welcome too. :-)

Metadata

Release files for django-polymorphic-tree 2.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-polymorphic-tree 2.1.1
File Size Uploaded Provenance Actions
django_polymorphic_tree-2.1.1.tar.gz 144.6 kB Without provenance Details for django_polymorphic_tree-2.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-polymorphic-tree 2.1.1
File Interpreter ABI Platform Actions
django_polymorphic_tree-2.1.1-py3-none-any.whl Python 3 none any Details for django_polymorphic_tree-2.1.1-py3-none-any.whl

Total release size: 303.8 kB

Release files / django_polymorphic_tree-2.1.1.tar.gz

Download URL django_polymorphic_tree-2.1.1.tar.gz
Size 144.6 kB
Tags Source
SHA-256 checksum
How to use checksums
84091e43d99687f226a62dcc720f8ca876f1b2f64ff611c86ac65b30ceec49fc
BLAKE2b-256 checksum
How to use checksums
4a889151a1cc9774d20251e83490b3f8d48662f7ae1b54a82de3d04d128d448e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Release files / django_polymorphic_tree-2.1.1-py3-none-any.whl

Download URL django_polymorphic_tree-2.1.1-py3-none-any.whl
Size 159.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
17293890abd06a54a78c981db7053d949f29b9b105a2f136990ffcae841186c8
BLAKE2b-256 checksum
How to use checksums
387f96dba112f5a58ace0bfa7c1b60f240b388f37ec16622f453fd0cc73413ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Security for django-polymorphic-tree 2.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page