Using django-mptt TreeNodeChoiceField in a TabularInline admin form
You can also be interested in:
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!
Your Smartwatch Loves Tasker!
Your Smartwatch Loves Tasker!
Featured
Archive
- 2021
- 2020
- 2019
- 2018
- 2017
- Nov
- Oct
- Aug
- Jun
- Mar
- Feb
- 2016
- Oct
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2015
- Nov
- Oct
- Aug
- Apr
- Mar
- Feb
- Jan
- 2014
- Sep
- Jul
- May
- Apr
- Mar
- Feb
- Jan
- 2013
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2012
- Dec
- Nov
- Oct
- Aug
- Jul
- Jun
- May
- Apr
- Jan
- 2011
- Dec
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May