# Hidden gems of Django Admin. Part 1 - Maxim Danilov

Source: https://djangotv.com/videos/djangocon-europe/2022/djangocon-2022-hidden-gems-of-django-admin-part-1-maxim-danilov/
Date: 2022-10-14
Speakers: Maxim Danilov

## Summary

Maxim Danilov presents Django Admin as powerful but full of hard-coded, undocumented behaviour that developers often work around. He shows ways to structure admin configuration, automatically register model admins, preserve application and model ordering, and create and route multiple admin sites with permission-based access. He argues that Django’s singleton ModelAdmin design causes concurrency and performance problems, and proposes creating a fresh instance per request so results can be cached. He also demonstrates adapting class-based views for admin actions, replacing the built-in action permission approach, and turning admin responses into JSON APIs with a small amount of code.

## Transcript

### [00:00] Introduction to Django Admin

[00:00] My name is Maxim Danielev and today I want to speak about an important part of Django. I want to speak about Django Contrib Admin. I work with Django Country Padmin around seven years. I start to work with Django from Tw twenty thousand thirteen and from twenty two thousand fifteen I work explicitly with Django Country Padmin. I want to say thanks for my team. Anastasia Sen created this presentation thanks Anastasia

[00:46] Our senior developer Pelikin Pavel tested all my created all my crazy ideas and Martin Achenreiner is our intern. He tested all of whole code Thank you Martin. I'm owner from Webasoft company and mostly what we do at work we drink. Yeah, we drink wine. We serve a bitgest database about alcohol about wines in Europa. And Everyone had one incredible project in

[01:32] own life or pet project. And my pet project or mine crazy idea, I want to use Janga Country Padmin. So much as possible and I won't I don't want to change much or I don't want to overwrite a much in this library I think this library is really powerful. First words. DjangoConTrip admin is buggy and has hardcore. What I mean. Django country padmin is bugged and in Django Country Padmin we have many hardcodes. All is hard-coded.

[02:17] URLs, names, variables, constants, settings all is into the code. If we want to change something we should to override it. And of course, all of that is not documented. Completely not documented. Something what we can find on Django project, this is a one person from this library. Okay. And right now we should speak about different undocumented feature in Django Country Padmin. At first to start, I want to create one app in my project.

### [03:03] Admin Configuration

[03:03] In this app I need only two files I need files app and some other files. And to start to work with admin panel in Django we can create config class which can set up our admin panel. Somebody understand or if I say admin panel in Django? Who can understand it? Okay. And admin config help us to set up the this admin part of Django

[03:49] and Of course, we can create additional site admin class which shows us the whole information. And I already defined this class And it's all normally this you can still find in documentation, and we can override some small elements. And after that we should to define to write my new application with admin site class and with admin config In setup of my project, and in documentation we can find this

[04:35] example. And I think this is wrong. Really this is wrong. Why? I can define it normally. I can define it simply to write name of my project. I don't write to I should not I don't need to write the full part to the admin config. I can it Django take it from my application automatically. And why I think we should do it like this If we start to work with big projects, the good praxis we should

[05:21] define at first. Bulletins application at second part we should define the third party application and at the end we should define our local application. And if I should to define something above on in the other art mm I don't like it. If a new developer come to my company they don 't cannot understand for from the first glance how it works, what he should to do. And of course we can do it a little bit better. We can split our setup on the three parts and after that if

[06:07] we want to override something automatically it's mm lighter to override. The one undocumented feature is we cannot in early parts of Django we cannot define admin after the admin docs application it not works but thanks for last update from django right now it works i can define admin behind the admin docs probably it's it's here. Yep. I can add okay. Admin docs right now we can put admin docs

[06:52] in our apps install it apps everywhere. Thank you for developers of Jenga. And The last part what we should do, we should define the URLs, which contains the whole part of URLs of admin site. And in documentation we can find this example. And a little bit later I show you this is wrong, or probably wrong. Okay, next step. If we start our admin panel, we see it works, but something wrong here, I think.

### [07:38] Automatic Model Registration

[07:38] What I mean Next our feature as is this is model admin auto registry If I start to work with my new project, I create for example three models. I have a product, I have a shop and I have images for products. And I want to register it on the admin site. I should create model admin classes. I should import models from model PI and I should also import admin registry to register my model admins. It's really

[08:23] complicated and it's a really Not clear why it's so and if I start my new project only with two model admins I receive What the what the hell? I have my model admins and something comes without me self Of course I know this is already registered mm model admins for model But why it happens? Okay, answer mentioned in documentation. We can don't use We can use simple admin config and this is not happens.

[09:10] And admin config On RAIDI of all apps created out a registry for all mo all applications. And I think this is a good point to create something bigger. What I mean? If I override this method and after call super, I can collect all apps config After that, I can ask for every appconfig. Hey appconfig, are you have a model PI? Wait, admin PI? If model admin asked me, yeah, you have admin PI for this app, I can go through full

[09:58] models in this application and I can register these models with classes with which I can find in admin PI. But the important thing I should name these classes like model name and admin For example, I have product, I should have in admin PI I should have a class which named product admin. What I can to receive In if I do it all manual with hands I should import models, I should I should import registry and I should create

[10:45] classes model admins. If I do it automatically, it happens automatically. If I don't want to register something, I can simple to change name for model admin class. Oh yeah for yeah for model admin class. And they have the we use it from young Junga version and we It happens automatically and I can say it's easy. Right now, if I start a new project, I add this method. At first what I do I add this method this is simply we can register our models

### [11:31] Admin Application Ordering

[11:31] automatically If somebody don't understand what I want to tell right now, you can read article on Medium about this possibility. Then next out ordering of admin list. If I start if I start my project, what I can see I see this is the sorting of my apps and models. Without logic or without again humanity. It's automatically ordered and why? Yeah in our site admin

[12:18] We have a function or we have a method which made many loops at first The first loop we collect all models and apps. The second loop we sorted it in alphabetical order. And after that we have again one loop to go truth and there we go through every application and there we can sort also model names. We need more loops for God of loops, but not for our project In our project they can throw away all these sort loops and

[13:03] healthy method of which collect all names for application. I leave only loop which collect for us methods and applications and accordingly declaration our application in setup install it apps we can receive order of apps and accordingly how I define my methods in my methods PI I can receive this order You can see I create a shop model and image model and product model and I see the model

### [13:48] Multiple Admin Sites

[13:48] admins in order which I want. I want to control this order and also I can control in which order came's application on my model admin on my admin site. The next feature has multiple admin sites. Who knows about this possibility in Django? Yeah of course developer part knows but somebody who worked with FET yeah who has for example five model admin sites on pro in project Okay, nine, ten? Nobody. Okay. Multiple admin sites is

[14:34] Perfect thing. There we can simple grouping we can create Groups of model admins, and we can work only with this group. We can create permission-based URL group access. is a s really simple and easy and we can w work with group of my managers of my admins it s works much easy and of course If you have a big project, you can split development of every more admin site on different teams. and they can work independent

[15:20] from other teams. Why we need many admin sites. For example A guns simple example I have e commerce platform and I have managers who work only with products Therefore I have content admin. Also we have stocks Manager from stocks works only with stocks admin and also we have a big bosses they want to collect stats of shops or stats of stocks and they goes with own

[16:05] Admin site Ural And they receive their own, they achieve their own goals. Register multiple admin sites is easy. We should create a new class of admin site and we should create an instance from admin site and only one argument to create a new instance is a name of admin site A big problem in Django, okay, nicht problem. Big on the undocumented feature in Django is we have one default admin site, and this default admin site by default is registered the name admin. And

[16:51] this brought us last 10 years some problem, but Yeah, I know how we can solve it. Register admin URLs. In documentation we For every new admin site we should create we should import admin site and we should put path in mind dispatcher orel dispatcher but really we really should do it now Easy registry or healthy model admin registry is every instance from model admin

[17:36] is registered in admin sites. In sorry, in all sites registry. I can collect in my dispatcher URL all sites registry, I can go through I can go through every admin site. I can take name from this admin site and I can register it in path. For example, how it seems before with manual registry and how it seems when you use automatically registry admin site. Of course If you if I create a new admin site, it can be so forth registered. I don't need to change anymore

### [18:23] Admin Namespaces

[18:23] anything I like it and that's why I think it should be in documentation or it should be created automatically if I start a new project. Okay, we can go wider on to the next slide. And there we have a problem. I take the these strings from documentation. It's a corrected version. In documentation, you can find something other, but if you want to resolve a any function for model for admin site you can use this rule admin

[19:08] like a name of admin site, twice points and after that up label and the model name. And I can only ask, really? It's really works? No, it's not works. For example, I open project. You can you can check all my idea in repository link you can find on the end of presentation. And if I start my project on the back end this URL admin index works like trolls meet trolls me

[19:54] me to the one admin site and on the front end. At the same time, this URL gives us completely other link. What we can to do, what we should to do. Of course, we should always use namespace Which admin site I want to start right now, or I want to call right now. This admin namespace we should use everywhere. In admin panel or in front-end. Please don't forget about it, but for backend for default templates it should all

### [20:40] Permission-Based Admin Access

[20:40] be it should be all overridden Right now we have hard coded their namespace admin. It's wrong. For multiple admin sites, of course. Permission -based access. This is perfectly, I like it. I can stop access for everywhere to for the special no for the special admin sites and we have an method names has permission every request which goes through for admin site every request calls

[21:27] this method and there we can check If this user has permission or not. And I use here a special function from Jjango. I check really permission by this user. For example, superuser. has all permissions but they don't have it. We have a checkbox super user. With this function user has perm I can check If this super user really has this permission which I want. And additional permission, zum Beispiel this permission is out stock managere. Ta esas inju permission.

[22:12] We can kreeta it simpli truth model meta. Thanks for Jenga we can create it simply, we can define a new permission, but After that we should tomate migration and migration created in Upermission but migration don't delete any other old permission and therefore if you have a big project more than seven years development history Probably you need also to register permission admin to check and remove old permissions. Most important right now we go to the most important feature in

### [22:58] ModelAdmin Instances and Caching

[22:58] Django Country Padmin, SS model admin class. I like it Thank you for developers. It's a beautiful really I love I love this model admin class, but I understand this is this is really have a many problem. More than Admin class it's seems like view set from Django Rest framework or it seems like Clays based views But it break every model admin class break down the idea from generic class based views and modern admin class don't have enough class based views.

[23:46] Functions, or the methods, features. Etc etcetera many hardcodes and But we have mostly a problem. Every model admin class, every model admin instance is singleton We cannot create more instances from model admin class. Why it's a problem. Till today it was not a problem. Yeah? For most developers not a problem, but not for me The first problem. If we if I have two users who work in the same moment with the same instance of model

[24:32] admin class, this user cannot store all data in this instance. We cannot use instance like a container for data. Why? Data from other user can be removed The second big problem, I don't like this part of model class. If we cannot store the results of internal method calls We should to call these methods more and more and more time. For example, for one simply get request. We should call ten methods thirty-seven times. Really?

[25:17] We really should to do it to work with model admin? No And I show how we can change it. All changes last 10 years in Django Country Padmin subordinated to this singletone design. And how we can change it? Simply. Problem lays in method model admin get URLs in last string we returns the returns URLs but Please, can you see what is wrapped in this return

[26:02] In Oral in model admin is wrapped instance, a bounded method of instance. If I compare it with class-based view, in class base view If I have Class Base View, Class Base View returned Fabric for instance. For every request for Class Base View created a new instance. For every request of model admin, always returned bounded method of instance. It's wrong How we can s how we can solve it? Answer lays on the some lines above. Wrap method this is

[26:48] Method of our admin class. Admin class wrapped this instance. Okay Thanks. I can create a fabric which receive instance and after that I get instance from bow. function. I check if this instance is model admin class instance. And after that I can create a new instance. And after that I can return call of new instance for every request. That's all. If you can do it, we achieve we can use a model admin class instance like data container. Hello, like a data container. If

[27:33] we can do it, we can store our results in instance we can st keep user request something else. At the second we can cache heavy methods for in model admin and What we can achieve to cache only four methods. We can increase twenty percent of our time. We can increase in reality for heavy post request we can achieve it

[28:19] Till seventeen seventy percent of time. It's really huge. And for n f for future. If we use it in Django and if we integrated it we can after that simplify model admin class. Right now as this is yeah fast thousand lines and right now they have around six hundred loops which can be cached I think we can we can much it better. And read a little bit more if you don't understand why is bad or why my solution, we need my solution

### [29:07] Class-Based Admin Actions

[29:07] You can read it on the in article. And we right now we can go in a little bit deeper. Model admin actions. Who knows about model admin actions? Thank you. Model admin actions is a really crazy perfect thing in model admin. I like it. I really like model admin. What is action in Django by default? Action in Django is a function. We declare this function an attribute action in model admin. This beviously is a function

[29:53] based we don't have any permission. Admin decorator is completely wrong and some function added globally. Confirmation page is immutable and confirmation page has really huge performance problem. That's why we should to improve it. My idea is I want to use my class-based view to like a action like an action. But I should to keep a background from model admin class. On the last post we should return nothing

[30:38] at first and at a second I know why but at a second the call of every action Switch their call parameters. For normal class-based view, at first comes request. For action at first place comes model admin class, model admin instance. What we can do? We can in this case override three methods of standard of base class view and I swap on dispatch. And simply swap dispatch first hello and second. Completely no, uh-huh I work

[31:24] On dispatch I swap on dispatch two arguments, I swap on the setup two arguments, sorry, I speak mostly on German and sometimes I speak German, sorry And on the last post I returns nothing. This is only example how I can do it And after that I can declare my class-based view with these changes. I can create wrapper. I can create I can declare it like standard in dispatcher URLs and of course I can wrap this it in action which exists in Django

[32:09] but we should not use this decorator We can use inheritance, we can use much more if we start to use generic class base view. In reality, it can be really huge declaration with some information for manager and only one small function process which change something with object in query set of object And this example is from our old project Here is shown deep inheritance in admin

[32:55] classes. And of course, every class-based use action I can mm I can use in many other model admins. But action permission, action decorator permissions. What's wrong with action decorator? I know decorator permission required from Django. I know for example user permission I know it. And I see at first time I see action decorator I write permission. User is stock manager and it simply don't work What why?

[33:41] I start to work and I understand the developer of action declarator Created in UART of permission as a middle text in name of method in model class For example, I use word stupid and I should create a new method in model admin has stupid permission. At the second problem is SSNU art how permission works. Why? If I write two permissions they check by any, not by all.

[34:27] I mean if we first has stupid permission method return files After that, it calls has view permissions, and if manager don't have any stupid permission, he can call this function. And but I won't what this manager it should be checked the both permission not only one of many permissions And that's why I think this is completely wrong. Solution is please to avoid use this decorator. from Junder. And you can simply define a permissions attribute for function or for class based

[35:15] use and We should only to override filter action actions by permissions. There we can create One liner which checks if this function is if this action has per don't have any permission or if this action has permission and user has this permission too. This is only one liner, fear five six here is three lines, but it's really we should to do it if we want to work correctly with permission for actions.

### [36:00] Headless Django Admin

[36:00] And the last thing which I want to decl to tell about model admin I like model admin. I can simply in two minutes change all what I want or create all what I want. But sometime we have not only static model admin also we have any reactive head who has reactive head for admin solution Reactive backend or something. Nobody, don't matter. And I want to create headless backend

[36:46] Not from scratch Django is a framework for perfectionists mid deadlines. I don't have any time, I have no deadline. That's why in Janga exists already exist two views. One is mentioned in documentation but not documented. this view give us the full translation and full localization by Ajax request and the other view give us a possibility for autocomplete

### [37:37] Admin Views as JSON APIs

[37:37] Okay, I don't know why. I can read the answer, of course. And how to idea how we can transform every admin view or every admin model admin view into API. It's simple. Every admin view returns one response. If we have in this response template, we have a context which should be put in this template. In this moment I create response for index for admin side and I wrap this and instead this response I take

[38:24] json response and I put only a context for response in json response. Of course I use special encoder, my JSON encoder The solution for works for full model admins if I override on admin side. Again the admin view. I overwrite it and I wrap every response in JSON response If I call admin site, if I call admin site with iax method

[39:09] The magic lays in the encoder. I take the encoder from Django, it's already exist, and probably you want only to add something how this encoder encoded action form, admin form, change list model and HTTP response redirect. And after that, every answer from admin side we can receive, I use postman to check it, we can receive in JSON form. That's all. Every URL in admin site we can transform in API only with seven lines of code.

[39:56] That's all I can change every model, I can change every object, and I don't write any new serializer and API. That's all. The Django admin or the Django Admin Contrib model is a really huge and powerful toy. I like it And let us to use this power. I continue my talk on the Django Korean United States there it was it should be advanced talk. Why? It can be a little bit harder than

[40:42] Today and there i want to tell about inlines i want to tell about djung nested inlines which exist from early version of Django but nobody knows about it. And yeah, I want to tell about Dumnet related widget in admin form. And I want to tell about bound that bound that autocomplete and admin forms and yeah many other things. Thank you My name is Maxine Danilov, Korean repository.
