We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Ultimative session about hidden gems of Django Admin

00:00

Formale Metadaten

Titel
Ultimative session about hidden gems of Django Admin
Serientitel
Anzahl der Teile
141
Autor
Lizenz
CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 4.0 International:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben.
Identifikatoren
Herausgeber
Erscheinungsjahr
Sprache

Inhaltliche Metadaten

Fachgebiet
Genre
Abstract
The Django Admin Panel is a complex and bad-documented tool in the Django that can greatly speed up development if you start to understand it. “Isn’t it easier for us to write our Backend?” I will answer: “No, it’s not easier!”. 8 years of insights and discoveries in my Talk. Here i want talk about multiple admin sites, ModelAdmins possibilities, object state versioning and app configs as completely forgotten hidden power.
114
131
Divergente ReiheProgrammbibliothekSystemverwaltungSpieltheorieComputeranimationVorlesung/Konferenz
DokumentenserverSoftwaretestBimodulLokales MinimumTypentheorieInhalt <Mathematik>Produkt <Mathematik>Web SiteVererbungshierarchieURLEndliche ModelltheorieBildschirmmaskeGeradeSoftwareentwicklerBildgebendes VerfahrenVererbungshierarchieWeb SiteProgrammierparadigmaProdukt <Mathematik>Kartesische KoordinatenKonfigurationsraumObjekt <Kategorie>DämpfungMathematikSystemverwaltungDokumentenserverSchnelltasteMultiplikationsoperatorDeskriptive StatistikURLProjektive EbeneBitMultiplikationSchnittmengeCASE <Informatik>MomentenproblemVideokonferenzVerschlingungFamilie <Mathematik>Coxeter-GruppeGruppenoperationKeller <Informatik>NormalvektorDivergente ReiheComputeranimation
VererbungshierarchieWeb SiteBimodulProdukt <Mathematik>Inhalt <Mathematik>Web logFAQKategorie <Mathematik>URLSpeicherabzugEndliche ModelltheorieGruppenoperationMathematische LogikAutorisierungMathematikSpezialrechnerInformationSichtenkonzeptServerInstantiierungDatenmodellWrapper <Programmierung>Exogene VariableDefaultMittelwertOrdnung <Mathematik>SystemverwaltungBildgebendes VerfahrenKlasse <Mathematik>SoftwareentwicklerGamecontrollerProjektive EbeneSichtenkonzeptInstantiierungKartesische KoordinatenEndliche ModelltheorieElement <Gruppentheorie>Web SiteApp <Programm>Mailing-ListeGeradeServerCodeMultiplikationsoperatorMathematische LogikDatenverwaltungTranslation <Mathematik>MathematikDokumentenserverPatch <Software>ResultanteNeuroinformatikPunktInhalt <Mathematik>ProgrammierparadigmaInformationsspeicherungNatürliche SpracheGenerizitätTouchscreenMinimumRechter WinkelProzessautomationComputeranimation
Exogene VariableDefaultGruppenoperationVererbungshierarchieDatentypE-MailVideokonferenzSystemverwaltungGruppenoperationProgrammbibliothekEndliche ModelltheorieInterface <Schaltung>DatenverwaltungFunktionalStandardabweichungProzess <Informatik>MathematikDefaultSpeicherabzugSichtenkonzeptVideokonferenzAttributierte GrammatikKlasse <Mathematik>GenerizitätProgrammierparadigmaObjekt <Kategorie>MultiplikationsoperatorSerielle SchnittstelleSchreiben <Datenverarbeitung>InformationFront-End <Software>Response-ZeitDebuggingDokumentenserverCodierung <Programmierung>InternetworkingTemplateProjektive EbeneFramework <Informatik>Exogene VariableGeradeKontextbezogenes SystemProdukt <Mathematik>GarbentheorieWort <Informatik>Geschlecht <Mathematik>Mixed RealityPatch <Software>Arithmetisches MittelElement <Gruppentheorie>Formation <Mathematik>CodeMomentenproblemObjektmodellComputeranimation
VideokonferenzDatenfeldAdvanced Encryption StandardDatenmodellVererbungshierarchieTermHypermediaAbfrageWidgetDigitalfilterDokumentenserverObjekt <Kategorie>Elektronische PublikationEndliche ModelltheorieSystemverwaltungDatenfeldElektronische PublikationBildschirmsymbolSichtenkonzeptAttributierte GrammatikObjekt <Kategorie>Wrapper <Programmierung>StandardabweichungWidgetProgrammfehlerGeradeCodeROM <Informatik>Kontextbezogenes SystemDefaultVererbungshierarchieVolumenvisualisierungDokumentenserverBildschirmmaskeMathematikZweiVersionsverwaltungZahlenbereichRechter WinkelDatensatzDatenbankPhasenumwandlungMultiplikationsoperatorFehlermeldungSchreiben <Datenverarbeitung>GruppenoperationAggregatzustandProdukt <Mathematik>ProgrammbibliothekInformationFunktion <Mathematik>ResultanteVideokonferenzRelativitätstheorieLoginKonstruktor <Informatik>SkriptspracheProgrammiergerätRechenwerkTabelleMeta-TagFormation <Mathematik>Domain <Netzwerk>Lesen <Datenverarbeitung>TemplateAbfrageStandardmodell <Elementarteilchenphysik>Elektronisches ForumTexteditorSoftwaretestComputeranimation
Transkript: Englisch(automatisch erzeugt)
I'm very glad to see you here, and I hope you enjoyed my talk. Today I want to speak about hidden gems in Django Country Padme library. This is a long series of talks.
I started to speak about it in 2021, and yeah, it is my fifth or sixth talk about Django Country Padme. I work... Who am I? I don't know.
I am Maxim Danilov. I work like a software developer around 25 years, and last nine years I worked with Python and with Django. And last eight years I worked exactly with Django Country Padme. Four years ago I started to work also with Vue.js and Nuxt.js, and I have a series of
talks also about how Vue.js works with Django together. Okay, all examples you can find in the repository, all my talks you can find in the repository,
and links to other video talks you can find in the repository. Before I start, I want to say special thanks for my previous team. Anastasia always created for me design of presentation.
Pavel Pilikin implemented all my crazy idea, and Martin Aachenreiner tested it. Folks, I miss you, but yeah, something happens and we try to see what happens in future. Also, special thanks for my family.
Thank you for my wife who support me. Thank you for my children, they await me at home. And thank you for my animals, Marcel and Kisa. And thank you for companies who support me on this conference. Nobody is here, and yeah, I don't know who appears here on the next talks.
Okay, basic steps. Before we start to use Django Cantrip Admin, we should create models. Are you know about models in Django? Who knows about models in Django? Thank you. Thank you.
In this case, I create two free models. I create a shop, I create model product, and I create model image. Every shop can contain many products, and every shop and every product can contain many images.
This is only models. Till this moment, Django Cantrip Admin not works. Before, we should create model admins. I have created model admin for shop, model admin for product, and some inlines. I know about inlines in model admin.
Inlines has a possibility to change some binded objects in form, in change form from parent objects. This is, I show a little bit later how it works.
Okay, if you start your project from, or example project from repository, you can see add form for change data from shop. You can change title, you can change description, and also, in the same time, you can add some products to shop, and in the same time, you can add some images to shop.
Good or not, I cannot say, but this possibility add some products and add some images is exactly inlines. We have inlines form in parent form. Okay, in this talk, I compile knowledge about creating user-friendly
and developer-friendly admin panel based on the Django Cantrip Admin model. At first, we should register site admin,
but we should not register site admin. We should register site admin config in our settings PI to start to work with Django Cantrip Admin model. In the documentation, you can find this example. For my opinion, we can do something better than in the documentation.
My offer to you is to create an application which I call Admins, and I register this Admins application like normal. Why should we do it normally?
Because we can achieve readability in our settings PI. Everybody who works with settings PI can remember how huge these stacks can be. That's why I try to contain readability from scratch.
This is the only possibility. You can do all what you want in Django. I offer you to do something better on my opinion. And after that, we should register admin URLs.
Also, in the documentation, you can find an example. We register admin URLs if I work with paradigm multiple admin sites. I should register, I should with hand write every URL in URLs PI.
I think this is also not good. Why? Because we can make it automatically. In Django, we contain one container which knows about every admin site. And after that, I ask from container all admin sites,
and I take name from every admin site, and I register these URLs automatically. And after that, for me, it doesn't matter how many multiple admin sites I have, I have always only one line in the URL's PI.
And this all happens automatically. It's if I create new admin URL, it comes automatically. And of course, for me, it is better. What I mean about multiple admin URLs?
This multiple admin paradigm helped me to register some model admins only on the one admin site. This other URL, I can register other model admin. And after that, I can protect this URL group by permission for user.
For example, my translation can achieve only translation admin site. My content manager can achieve only content admin site.
That's all. Sometimes finance manager or tax manager should go only to sales. And I can give them only one permission. You can achieve this admin site or not.
It's much, much, much better than to work with permission on one admin site with whole list of model admins. Who has more than 100 model admins on the admin side? And this is possibility to split it on many admin side and work easily.
But again, I like automate all in Django. Django is funny. Django helped me fly fast and with fun.
But sometimes Django offers me to make something unimportant. For example, I should register model admin. This is standard example. I should import models, I should create model admins, and I should register appropriately model with appropriately model admin.
Too much work for me, exactly. What I want to do? I create a model admin autoregister. And after that, you don't need to read this code. You can see it in the repository. But what happens?
After that, I create admin PI. I write only model admins. And on start of my server, autoregister goes through four models, goes through four admins, and appropriate model is registered
with appropriate model admin. It's easy and I offer you. If you try to do it one time, you cannot forget about it. Every time I put this code in every new project, because it's amazing, easy to work.
Next step. Model admin ordering. I don't know why creator of this element put some logic against humanity. I don't know, I cannot answer why this application
and this model came in this order. I know, I know, of course. It's alphabetically order. But sometimes I want to set up myself. I want to decide myself in which order it came.
And I can change it only with one line. I should have a write get up list from admin side, from every admin side. I made it like a mixing. And after that, I can change order of application, appropriately order how I register my apps in setup PI.
And after that, order of model admins is exactly the same order how I define classes in models. It means I can swap shop and image
and image comes on the first place, shop comes on the second place. It's so easy, it's so nice. Try to do it. Of course, after that you understand what I mean. Jungle can be more easy, more funny. And I like jungle, sorry. I mean, we can take control of our project back.
Not from, we can take control from jungle developers and they can take it in our hands. Okay, the big problem about this problem, I tell many times, every model admin is singleton.
I know what means singleton. It means we have always in our project only one instance of model admin. Why is this problem? If I compare a model admin
and generic class-based views paradigm from jungle, generic class-based views paradigm, as is on the bottom of screen, in this paradigm, on every request, we create a new instance of view. In model admin, we don't create any instances.
It was created on the server start. Problem is, I cannot use this instance like a data container. I cannot store some results in this data container because if other user works in the same time
with the same instance, they can overwrite my data. This is a problem. But also, if I solve this problem, also we can increase speed. But some computation happens many times on one request.
I have a talk there I can show. Nine times calls one method. Four times calls other method. I can cache these computations results. And how I can solve it?
Solutions is easy, only four lines. On every request, entry point is admin view. On every request, I take this singleton instance, I create the copy of this instance,
and I call appropriate method of new instance. And this is easy, and it works. And every time on every request, right now, I have the new instance of model admin. We create this solution on Django 1.3, and after that, always we put this patch in our projects.
What we can achieve? If I store computations results in cache, I can cache it in data container. We can increase, we can win around 20% of response time.
20% already says something, but I can increase more. I can win more time if I do something else.
But try to use it. I write some articles about it in internet. If you don't understand what I mean, you can try to read it in an article probably there. You can understand better. Okay, next element, Django admin actions.
For my opinion, in Django country admin, Django admin actions, this is the best feature in full library. What I mean? Django admin actions help me to change many objects in one time.
Model admin gives me a crude interface to work with one object. Model admin actions give me an interface to change many objects in one time. But sometimes I want to work with actions in generic class-based view paradigms.
Django offers us only functional-based view paradigms in actions. Can I do something? Of course I can. I create a mixin which only patches a view class from a generic class-based view.
And this mixin helps me to convert every model admin action in generic class-based views action. Why I need it? At first, I can create action.
In this action, I can set up some attributes and I can create process. I can create child action from this action. I can override only process or I can override only some attributes. And this is much flexible than works with functions.
Try it and you also cannot forget this technology for model admin. I like it. But I should say a warning. Please don't use a default action decorator from Django.
This decorator is not safety. I already tell it on the other talk. And this decorator cannot work with user permission like, for example, standard permission required decorator from Django. I offer you simply to avoid this decorator.
I think it should be overridden in Django core. In Django country, pardon me. Sorry. A warning. How we can work with permission for actions? We can simply override this method from model admin class.
And after that, this all works. You can use it. For example, one permission change quantity for products can use, this action can use only stock manager. And I give this permission and only stock manager can call this action.
It's important and flexible. Okay. And we go to the middle of my talk. And important thing. Who knows about admin API in Django?
By default, we have only two admin API as I18th N internalization API and autocomplete view. But sometimes I see many libraries which create a new API
for crude interfaces for backend admin and after that they create their own reactive backend. But why they need to write this API? They already exist in Django. What I mean? All only what I need from Django,
I want to receive on every request instead of template response. I want to receive JSON response. How it happens? It's easy. The same view which I already overridden before. In this view, I catch every template response answer.
Template is not rendered yet. And I take only context from template response. And I JSONize this context like a JSON answer. That's all. And in this moment, with two lines of code,
I achieve full crude APIs for full model admins in my project. I don't need any Django REST framework for that. Of course, I have here one trick.
I use standard Django serializer. I override it as my JSON encoder. I like to use Django instead of other libraries. And in Django we have also serializer possibility. And I use Django serializer possibility.
In this solution. OK. This is standard answer from example. You can start. You can see it. And you receive the full information which you need to render template. Or you can use this information on the front end
to create some flexible backend front end for your manager. OK. I only offer you don't write new crude admin API. They already exist. But sometimes people want to create something new
because they cannot find it in existed library. OK. In the middle of my talk, all features which I already tell, you can find on the video or in repository and go on.
And we go right in my talk. Model admin get fields, have a back. Probably you should know about it. I create my model title in Slack. I create two model admin. In one model admin I declare fields like a fields attribute.
In other model admin I declare fields like a field set attribute. And if I call model admin get fields, and for first model admin I receive a title. For second model admin I receive title in Slack.
It means get fields not works normally in Django. And this not solved yet. And right now we go to deeper in Django admin, flowable inlines. Sometime you can see change form appears and after that we have some inlines.
But what if I want to put one inline somewhere in middle of admin form? I know many solution. They override templates. I don't know, something else. But in reality it's only two lines of code.
I create my read-only field. And on the render of this read-only field, I take from context inline and I render this inline on the read-only field. That's all. I take from context inline
and I put this inline instead of read-only field. But if I go deeper in this idea, what if I want to take some inline from other model admin and put this inline in place on read-only field?
This is nested inlines, which already achievable from Django 1.3. But nobody knows about it. Only four lines of code. But we have found it works right now.
You can use it. But we have some bugs, exactly bugs, in standard inline JS in default Django. And my team, we have completely overridden this inline JS. You can use it from repository.
Don't matter. I want to use nested inlines or not. My inline JS already remove some bugs from old inline JS. Many-to-many truth model. I need one idea. If I use truth model in Django,
custom truth model for many-to-many, I cannot change it in model admin. I receive an error, but not for me. If I use instead of standard model,
if I only change one attribute in meta, auto-create it, I add this attribute in meta, automatically it works. But please avoid it if you don't understand how it works. But it can be painful in future.
We use it already three years, this possibility. Okay, once possibilities I want to say. Okay, the first.
In model admin form, we have related widget wrapper. If I have some object from our table, appears some icons, special icons. Sorry, this widget is hard-coded in Django admin,
and I want to throw away some icons. How I can do it? You can see on video my investigation and offers, but the best solution we can say for widget. Please can view related files attribute,
and after that the view possibility disappears. This is easy, but we go deeper and related fields with auto-complete. Auto-complete already exists in Django from 2.0,
but we don't have many documentation about it. And it's easy to set up, but sometimes it works, but sometimes I want to see from United States of America, only region for United States of America,
dependent fields, how I can change it. It's easy. It works like a charm. You can see it, United Kingdom. How it works? Of course, with auto-complete. I should only override get search result in child model admin,
and I should give information for parent select, which child select should be changed. And it works. We created for that small search JS script,
but very important, we have found some bugs in auto-complete JS, default auto-complete JS in Django. And my team, we have overridden this auto-complete JS and removed some bugs. It's also in the repository.
OK, last idea, which I want to say today. Model admin form, object state versioning. We have many libraries which help me to keep version of object state.
Whoever seen this stupid construction? I have created it, but we should not do it. Why? We can use log entry. Sorry, error. Not log item, log entry. Django country padmin write on every state changes
the information about state. The last row, action time from last row, this is change time. The action time from first row for this object. This is creation time.
User from the last row is last editor. Creator from the first row, user from the first row is creator. And if I use subquery, I can create only one asking database
and it works like a charm right now. You can see, for example, last state changes happens in YULI for this product object. And we can state changes used for form safe.
How? Simply, I use this data stamp like versioning and on the safe, I check last stamp like a version number.
It works. You can use it and summary from my talk. If you want to write something, probably it already exists in Django. If you're a Django programmer, try to work with Django, not with Python. And try to learn Django, don't matter. Have your documentation or not.
Make Django not bar. Thank you.