abidibo.net

Using django-mptt TreeNodeChoiceField in a TabularInline admin form

django django-admin django-mptt

I use to use the django-mptt package to deal with tree like models. I also use to have my backoffice autogenerated by django admin.

Now one of the problems I've encountered was to add an inline form of a model which contains a "tree" field in a way the user can deal with a select input well formatted (showing parents and children in a clear way).

This task is easily reached in a normal form by defining the form field as a subclass of the TreeNodeChoiceField class provided by the package.

Well, the same thing has to be done to use such functionality inside an inline form in the admin, so we can do the following.

Imagine we have a TreeModel which is the model which contains a tree like field, called tree_field. Then we have a MyModel model which has a m2m with the TreeModel and we want to add an inline in the admin, so, in the admin.py

from django.contrib import admin
from django import forms
#... import the models
from mptt.forms import TreeNodeChoiceField

class TreeModelInlineForm(forms.ModelForm):
  tree_field = TreeNodeChoiceField(queryset=TreeModel.objects.all())

class MyModelInline(admin.TabularInline):
  model = TreeModel
  form = TreeModelInlineForm
  extra = 1

class MyModelAdmin(admin.ModelAdmin):
  inlines = [MyModelInline, ]
 

That's it!

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured