📜 ⬆️ ⬇️

Django admin trees

Editing models that are trees in the django admin panel is very inconvenient and unattractive. Immediately there was a desire to output a tree instead of a list of objects, for this you can use the wonderful jstree library.
To work effectively with trees in django there is mptt , which adds fields to the model for efficient sampling and methods for this, as well as template tags for displaying trees, etc.
If you do not use mptt, you just have a link to the parent - jstree can be connected to with the help of a single javascript, about this - a separate article .
Further about the models using mptt.

I wrote a base class for admin models using mptt. It replaces the view of the list of objects with its own, which displays a tree, adds ajax-requests to move the branches to a new location, rename objects and delete them.
Accordingly, the branches can be dragged to the right place, renamed, and deleted. Creating branches redirects to the view of the creation of the object, placing a link to the parent element.
Values ​​of several fields can be displayed in a tree branch. If any actions are unavailable for the user, they will be blocked in jstree. Clicking on the branch redirects to the edit view, right-click it brings up the context menu.

screenshot

To use this, you need to install mptt_admin:
')
hg clone http://code.tabed.org/mptt_admin/
cd mptt_admin
python setup.py install

Together with mptt_admin there is a sample project, you can use it for testing.

Add to acc. admin.py this code:

 from myapp.models import MyModel from mpttadmin import MpttAdmin class MyModelAdmin(MpttAdmin): tree_title_field = 'name' tree_display = ('name','slug','created|date') #name    class Meta: model = MyModel 

Templates are protected in MpttAdmin, he can give the necessary javascripts himself.

tree_title_field is needed for renaming, if you do not specify it, renaming will be unavailable, and the __unicode__ object will be displayed.
By analogy with list_display, you can specify several fields, and filters can be used in them, thanks to implementation features (except tree_title_field).

Source: https://habr.com/ru/post/85670/


All Articles