Back to the video

Hidden gems of Django Admin with Maxim Danilov

Transcript

By Maxim Danilov, Speaker 2, Speaker 3, Speaker 4, Speaker 5. From DjangoCon US 2022. Published November 2, 2022.

Watch the video Markdown version 5,130 words · auto-generated · en

Summary

Maxim Danilov shows how to extend Django’s built-in admin using features and extension points that are often undocumented. He demonstrates flexible inline rendering, nested inlines, custom many-to-many handling, autocomplete fields, related-widget permissions, and optimistic locking for concurrent edits, while warning that some techniques rely on internal APIs. His main argument is that developers should first inspect and reuse Django’s existing admin machinery instead of rewriting large amounts of code or reaching for separate admin packages.

Transcript

Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.

0:20 Introduction and Part One Recap

Maxim Danilov

Hello, my name is Maxim and right now I want to tell you about hidden games in Django Contrib admin model. This is a continue of my talk from Django con This is part two and I want to go deeper in this part of my talk. A little bit about me. I'm owner from small company from Austria, a company named WebSoft And it's a small team of developers. We I work with Django Science 2013 and Size Science 2015. We

me and my team we work mostly with Django Contrip Admin. Special thanks for my team who support this presentation. Anastasia Sen created slides for this presentation. Thank you Anastasia. Pavel Pelikin is our senior developer. He checked all my crazy ideas. And Martin Achenreiner is our in intern. He tested that all. My goal, I want to create user-friendly admin-based admin panel based on Django Contrib admin. How is it possible? I try to do it s already seven or eight years.

And before I go deeper, I want to do a small re recap of part one of my talk. It was previously on Jange Kon. EU 2022. At first I show how we can use better way to register a site admin config We can do it normally, it is not documented. After that I tell about how we can use admin site registry and how all of our site admins can be registered automatically. We should not change

URL dispatcher anymore with the small lines. After that I cover about problem in resolve function in Django If we use multiple admin size sites possibility. Problem also I provide a solution of problem. We should always use site admin namespace. everywhere and of course I understand the default Django templates in Django control admin they should be overridden Also, I show how we can use

permission based access to admin URLs And there I use special function from Django user has perm. This function help us to check really permission from a user. Don't matter if the super user or a normal manager, I check only permission, not checkbox from model. After that, I presented model admin autoregistry. This is an example from existed code. This model admins already registered and I don't import nothing. Low code, low imports,

low bugs. It's better than manually. And also I can say if I start every new project in Django The first code snippet which I copy paste as a model admin auto registry snippet. After that I 've cover how we can take back the control or in our project and how we can control order of registered model admin list on their admin sites and I open the big problem in DjangoCantrip admin: every model admin is singletone. It means for every request

we work with the same instance. And this is a big problem in compare these generic class-based views. Generic class-based view for every request Created a new instance and we can use this instance like container for our data. But it not works normally, it not completely works in model admin contrib. And I tell how in seven lines we can avoid this problem and after that we can cache results of method calls and we can improve speed of our admin site. More we can achieve more than 170%

faster than before. Yeah, we can make model admin faster than light. After that I show how we can use model admin in model admin action standard generic class based view as is really pretty in cute possibility we can after that use inheritance and we it is really scalable Please ask me how it works or you can see video it was published in internet And after that I tell what action decorator in Django is wrong and please avoid use this decorator completely.

They contain still yet stulner vulnerability and don't work with user permission and also i provide correct way how we can Use user permission for model admin action. And at least I show how we can transform our admin sites and full crude interfaces in admin in admin API collection to work with reactive frontend Loc the this is like a headless Django admin and for example after that I can ask developers from Django Rocket or Django

7:13 Model Admin Deep Dive

Maxim Danilov

3 Django boys, why you need to write too much code? It already exists in Django. Please try to use Django. This all you can find in internet by this link and This is a video. Also, you can find link on this video to full repository and two slides. After that, we go in deeper in model admin. Webisoft is creator from Vinepad. This is the biggest wine database in Europa. And what we do at work, we drink wines.

every day. It can be, for example, more than 40 bottles in day in tasting. And every time if I drink more wines, I start to understand Django better. And of course I should to say it here. I know probably the best chardonnay in whole world Came from California. I know. Thank you. Okay. And after the one day after the big tasting more than 20 bottles I create a new model and I create in this model only two fields. Title, Slack, don't matter

And after that I create two model admins. In first model admin I declare fields for admin form like a fields attribute. In second model admin, I declare fields for mod admin form like a field sets. After that I want to check how many fields in my form, in my admin form. And Unexpected I receive there only one field for first model admin and two fields for second model admin. Houston, we have a problem.

9:32 Inline Form Placement

Maxim Danilov

I open issue, I write problem in model admin, blah. I say it's a bug. Answer was issue was closed invalid and closed commentary. It's not a bug, it's undocumented feature. All what I try to tell in my talks, fast all these things are undocumented. And let's go to the different undocumented feature in Django Contrip admin. What we need? We need basic models. I create three models: shop, product, and image. Every product can be in shop, in every product can be an image, in shop

also can be an image. And we need three model admin. Shop admin, product admin, image admin. And also I create two inlines, image inline and product inline. To show it in shop admin form. You can see here already how work autoregistry. I don't think I don't need to think about manually register this model admin on the admin site. It works automatically. And if I start my project, it works as expected. We see at first admin form, at second, and on the third place

Inlines. And after that We go to the one problem flowable inlines in model admin. What if we have a big model admin form and we have more than 100 fields okay s usability problem But we want to put one inline somewhere in this small admin form and not behind. How it possible? Of course it's possible. How? Model admin contains a possibility like read-only field. In read-only field I can put all what I want. For example, hello San Diego.

How it works? It works. Sunday on the model admin form, I can put my information And this is important. This field render it before in lines which comes later. What I can do? At first I save in my model admin response and request on render change form. And after that, if com chems render for my read-only field, I render on this place one inline from context. That's all. I don't need to overwrite any something else.

How it works? It works. I put I simply put inlines someday in admin form. And if I put save, if I if I press save I do nothing It's not render, it saves completely normally. I don't need any do anymore. If you try to find any solution in the internet It's really huge big many-line code solution instead of only four-line solution. But of course if you don't understand what I want right now to say, probably my language is not too good. Mostly I speak German. You can read this information

13:23 Nested Inlines

Maxim Danilov

on Medium. I have an article, and you can try to under you can you can understand it once more time. Inlines, if we try to go deeper in inlines from model admin every inline can contain also read-only field. And I could can put a read-only field in inline Hello San Diego. It works like as expected. At first, model admin form, after that inline. In this inline we have

and read-only field. And what if I take other model admin And I make this other model admin ready to render, and I take from context from other model admin one inline And I put this inline into read-only field from inline for our current model admin. How it works. It works the same like a flowable inline, only four lines. At first I call I call product admin, there

is this small error I should I should use self model instead of product admin don't matter And I call for example add view. After that I take from context inline And I render this in line with current context in current model admin form. Only one problem we have here we should have right now request and response. That's why for inline instances I should overwrite this function in model admin and I should

through deeper information about self. Self has a small current model admin which contains right now request and response. And yeah, small remark. I use it with this generator and in Django Contrib admin we have around Six hundred eighty for loops and only seventy yields or generators. It's not enough. We can match our we can do our model admin faster if we start to use generator. But don't matter right now about inlines in inlines and if you start to render it

16:26 Nested Inline JavaScript

Maxim Danilov

how it works Wow, it works. But something strange is here. There might add a new project button, a new product button. Okay And here is important information. 50% or probably more code which prepared for us work with inlines lays in inline gs file from Django and problem is it's wrong Sorry, but this is completely wrong. It was created in 2009.

From many people it was changed. But it works not correctly. My issue was closed, Invalid, and you can say, Max it was not planned to do something like that, but my answer is stop when in JavaScript, I see one bug, for me it don't matter what was planned. We have a bug, we should correct it. And also you can say Max, you too much criticize all you do nothing for community. No. At first I write an article

how nested inline works and second we published inline JS which work for Whole line of Jenga from Jenga 1. 4 till last Janga and we have corrected this back. And also in this article, you can understand how nested inline works. Full solution contains around 21 lines. And right now I have a question to Developer from Django nested admin or Django nested. Boys, I you really need more than 600 lines in code. Probably we can speak about my about it after my talk.

18:44 Many-to-Many Through Models

Maxim Danilov

Probably you can use something of what already exists in Junker. And right now we can go deeper in our relations, relation fields Every inline to create any a any inline we need relation. And some problem we have if we start to use many-to-many in relation. For example, we extend our solution for product. Product can be produced in land, but probably, for example, ski, I'm from Austria. Ski we can receive from Poland, from Slovenian, the same model, and from Vietnam. It means

For product it can be free land lands there this product is produced. And also we have region where it was produced. And in this region probably I put one checkbox, this is a biological production or normal production. And also I want to create custom many-to-many model. Why? Sometimes Probably happens war in this region and product cannot come from this region in this moment, and I want to put off visibility of this region in this project. Product It happens, yeah, right now.

And if I want to start to work with this model in model admin, what happens Shit happens. System error. Why? We cannot use many to many field with custom with custom truth field Really? I cannot use it. No, I can I can use it. How? The best example is I can use proxy model. I like proxy model in our projects we have more than really much proxy models

and in with this proxy model for custom proof model I can declare like auto created model and What happens? It works. But please, you avoid it if you don't understand how it works It's important. It's a dirty hack to work with many to many with custom truth model, but if you don't understand it completely, please avoid it. But we have other problem in custom many-to-many truth model. Limit chases too don't work for

custom truth model completely. Really it not works? Or we can do something. We can try to search a way to solution. What is many to many field in our model class? Many too many fields add to class one descriptor. This descriptor returns us a menu related manager. And in this menu related manager we have many additional attributes And this many-to-many manager is child class of parent class, which is

data manager from our many-to-many model. It means we can override data manager from many-to-many model, and on getQuery set we can check. If this manager calls from many-to-many descriptor We can achieve fields, we can take from this field limit traces 2 and we can filter our result with limit traces 2. But don't forget, it's important. If you use prefetch related, we don't break prefetch related results

That's why I check before if something was prefetched, I leave it without changes and only on without prefetch it many to many a related manager I use filter with limit choices too. It's easy, it works. I like it more than smart solution, which also exists. Smart solution also we can override many-to-many descriptor. But we cannot do it. Why? Many-to-many descriptor is ein hard coded in Django. Many too many field

Used many too many descriptor strictly in code. We can override it. Some there in other galaxy also exists Django and we can define descriptor class for every field. But like for example file field, but not in our galaxy. And not for many too many fields. And of course we can change it. At first we should override contribute to class for many to many field And after super we should call set other and we can set our many-to-many descriptor. I think it should by be by default, but who I am?

I am only the developer. And What is with many-to-many descriptor? Many-to-many descriptor receive result, and if this result not prefetched. we can apply limit choices too for this result and we can work with that. Right now we use smart solution. In our project, I'm happy with that, but I think it should be changed in Django. I think Okay, relation field. We can go in deeper. In the related field widget wrapper

Maxim Danilov

This related field widget wrapper was my probably first what the hell if I start to work with model admin. Okay, it was for eight years ago and I start my model admin and I see behind the field related field some buttons Why? Why it happens? I don't see it in templates. How I can change it? Okay why it happens. It's hard-coded in base model admin for every regulated field mm every wrapper is wrapped In a related field

widget wrapper. And we cannot override it. Why? It's I we cannot easy to change it, it's in hard coded. Okay, hardcore it again, again and again. How we can change it? In 2016, I try a solution and I put loop through f full field in form and I set the deprecated attributes for every widget in form and some there it works some there is we don't need it. But probably it's wrong. If I have a form with

many than 170 fields, it's work really long. It's wrong. But you can find Django battery which do the same. The I try to find any solution and Solution probably to use other model admin. This related widget wrapper check permissions from other model admins. And it means we can in has add the delete change permission methods We can put check if this method called from

wrapper we can return false or true. It works. But not always. Why? For auto-created many to many related To check permission, in Django used one special function which checked full permission, not directly change or delete or add full permission. And if I have, for example, view permission true, also I receive again the fall buttons in line. It's not always work. Okay, last frontier. After eight years, I came again for to

function form field for Debbie field. I simply check name from every field and if I receive field there I don't want to see icons add change the let I change attribute for this widget. Right now this is the shortest way to work with related widget wrapper. But I think this is also not the correct way and we should have possibility to override this wrapper in model admin. But right now we don't have this possibility. Okay, it works. We have Austria and right now

29:30 Autocomplete Fields

Maxim Danilov

I put off the add and view possibility Next feature which really much asked in internet is bounded select We use bounded selects from Django 1. 4 till today. It works, it works for normal select, but right now we can use Django autocomplete, and it's funny to work with that Django autocomplete JSON view, not documented, issue closed, won't fix, it should not be documented, but we can use it. We use it also from front end for us. One only one thing

I need there is protection how many requests per minute I want to have this protection. We use it through Jungarest framework. Okay. To add autocomplete in model admin, it's easy. Documented, thank you. We add autocomplete fields, we shoot the declare search fields, and it works. I'm happy. But how to change results of autocomplete? Results of autocomplete we can change in function get search results. If request is Ajax,

we can take some get inf information from get request and we can filter objects accordingly these get requests But okay, in a little bit early from Django is Ajax was removed and I put isax back for this functionality, but it's important. We don't I think this is a wrong way to work with that How we can do it better? Right now is it is not possible in Django, but you can ask how we do it in our project.

Out of complete JSON view have a function getQuery set. and not function method and this method it's contains many lines of code you can check it But developer who created this code probably forget about changeless instance which do the same. I can only ask probably you cannot check this code already exists. And if we create get changelist instance and if we ask query set, query set made the same. But also get change list automatically

Works this gets with query string and get changelist instance made all met made filter for my objects automatically It means probably we should overwrite or change out a complete JSON view and probably we can use get changelist instance to receive the results of autocomplete. But right now it's not possible directly in Django. Okay. Also we should give information for our select how they bound that

and on change from parent select we should send any information to child select In this case, land is parent select, child is region select, and on change I start function search. Function search is completely easy and it contains try function why. Django use autocomplete JS and there is some function is really hard coded we cannot change or add any parameter in search string That's why function search should find

child elements and after that they wrap send data method in new method and add some parameter which I want. Okay, little bit hard, but you can find it in repository and it works. How many lines I use? Two lines in Python and nine lines in JavaScript. I check Germany United K UK or something else. It works. And if you don't understand what I want to tell, you can you can read about it

on Dev2 in my article. Sorry, it is not published yet. I don't have any time. I try to publish it on the next week. And this all it's perfect, but at the end Sunday we should press button save And what we can to achieve. On the last version of Django, if we work with multiple manager in the same time on the same model admin and somebody adds an inline, somebody delete an inline, we can press save and we can receive

34:50 Admin Form Versioning

Maxim Danilov

this message. And this is a famous problem in Django forms. For hidden fields, we don't see the don't see error message. Of course I know how we can change it, but right now a problem not in the error render. Problem many user try to change the same objects and at the same time. And I think we should use existing Django versioning possibility. We can do it through Jenga admin log

for every model which we use in admin panel We can add attribute log as a generic relation to log entry or to Django admin log. And we don't need any migration It's important. It works normally without migration. We can use it right now in every Django project. After that On render change I sent in model admin form information about time one state of object was last time ch change changed in initial and after that

I should create one field updated they contains my data from last change and on clean from my form I check if the data the same, time the same, microseconds the same. I think nobody changed this object Or I throw an validation error, but I made it a little bit better I don't throw error, I add error to form, and I use all. If I use all, I receive error message not in field.

I received message on the top of my form. How it works? Please correct the error and after that the object was changed in this time Of course, for normal project we should do a little bit more, but right now as only example how we can use versioning which already exist in Django. And yeah, we can we can use many things from Django which already existed. Like summary of my talk for today, I not cover many things which I collect in the last eight years in my work, but summary.

38:37 Key Takeaways

Maxim Danilov

The code which you want to write probably already existed in Django And if you think you are Django programmer, please try use Django instead Python. We have too much Python and too low Django in our project. I'm so sorry about it And of course, please try to learn Django. Never mind. It's not well documented, but it's it's perfectly thing. I love it. And it's it's amazing. Please

take time and try to learn Janga. Read the code, read the articles to go to the conference. Make Janga not. Thank you.

39:45 Questions

Speaker 2

So we do have some time for questions. Would you like some easy questions?

Maxim Danilov

Okay.

Speaker 2

Your slide says not difficult ones. So I'll s I'll start off with an easy one. When are you going to publish that DevTwo article? Was it next week?

Maxim Danilov

I hope next week.

Speaker 2

Cool. That's my one question. Has anyone else thought of a question yet? Make me read

Speaker 3

Yay. Thank you so much for your presentation. I d there's a lot of opinions in here. That one of which I I'm not sure if I understand the documentation one. I love Django documentation. So I'm under I want to know where you think the Django documentation could be lacking and then also what we could do to improve it and how we can move forward with that

Maxim Danilov

Thank you for question. I think Django documentation covers around 10% of all possibilities of Django. For example, we don't have any documentation about query set query. It's really huge and powerful part of Django, and of course we don't have We have only 10% documentation about Django Country admin or full Django Country collection. And I try to make the world better. I write article mostly on Russian language, mostly on medium

and Probably I can try also to contribute in documentation, but my English language probably should be better for it. Yeah. I hope I answer.

Speaker 2

Any other questions, Johns? Oh.

Speaker 4

Thank you, Katie. Maxim, great talk. I was interested by the example where you were nesting an inline from another admin in an inline.

Maxim Danilov

You want to see it.

Speaker 4

Well, I remember it and I th you explained the rendering. But what happens at the post? How do you save that inline? Because How do you save it back? So if you

Maxim Danilov

How I can send results on save button. Yeah, answer lays in article. Yeah, sorry, I don't cover all, but what all we need to override at first we need override is changed. This method in form to give info what this inline in read only field was changed. at first and of course on save we should recursive send ask for this field this field should be s saved and of course this inline came from other view it means on

Save this inline send signal to other to other view to save yourself. It's it's really three four line of code i in reality. Yeah But it's completely work a worked solution on in article. You can you can we use it already Please, better.

Speaker 5

Yeah, it's really interesting. I'm curious like kind of what your take. So I my understanding is when things are undocumented. Oh okay. When things are undocumented, it kind of means the developers are free to change them at will and there's not a guarantee of a Any kind of like API that's cons you know necessarily consistent between versions. How has your experience been kind of maintaining some of these solutions that may be leveraging like undocumented APIs in the Django admin cross versions, I guess.

Maxim Danilov

We all solution which I provide right now in my talks works from Django 1. 4 Till Django 4. 1. 2. Of course, every time I need low code. Django improve yourself. That's why, for example, for Django 1. 4, I need a little bit more code. But every step it it's low and low and low and low. Right now for Django action I threw away from our project a matchline of our existed solution.

Why? Django had it itself. I think we can use Django for better solution and right now we have Really good possibility from Django. Django version 4, I love it. It's really a tool which I like. Thank you for developers. Thank you.