M
M
Maxim Zubenko2018-09-03 18:46:17
Django
Maxim Zubenko, 2018-09-03 18:46:17

How to make the right order when displaying models in the Django admin?

My admin.py file has the following order

admin.site.register(TypeProfile) # Вид профиля
admin.site.register(TypeFacade)  # Вид фасадов
admin.site.register(Price)       # Формирование цен
admin.site.register(PaintColor)  # Цвет ЛКМ
admin.site.register(PatinaColor) # Патина
admin.site.register(Materials)   # Материалы
admin.site.register(Category)    # Категории
admin.site.register(Products)    # Изделия

And in the admin panel, everything is sorted alphabetically:
Types of profile
Types of facades
Products
Categories
Materials (workmanship)
Patina
Pricing
Color LKM

How can I make the models display in exactly the order that I specified in admin.py?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Zubenko, 2018-09-03
@JawsIk

In general, I found the sorting function. It sorts in the get_app_list function of the AdminSite class . Then, at the direction of Pavel Denisov , he began to look for solutions. I found different options, so by combining I got the following option. All manipulations take place in the admin.py file .
Here I immediately want to make some digression, that when the registration is reassigned, Users and groups disappear from the admin panel and therefore they need to be registered there yourself. But first things first.
1. We make the necessary import:

from django.contrib.admin import AdminSite
from django.contrib.auth.models import Group, User
from django.contrib.auth.admin import GroupAdmin, UserAdmin

2. We define our class, inheriting from AdminSite and rewrite the function in it. (in my case, I just commented out the sort loop):
class MyAdminSite(AdminSite):

    def get_app_list(self, request):
        """
        Return a sorted list of all the installed apps that have been
        registered in this site.
        """
        app_dict = self._build_app_dict(request)

        # Sort the apps alphabetically.
        app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())

        # Sort the models alphabetically within each app.
        #for app in app_list:
        #    app['models'].sort(key=lambda x: x['name'])

        return app_list

3. Replace admin.site with our own:
4. Register our models:
# Register your models here.
admin.site.register(TypeProfile)
admin.site.register(TypeFacade) 
admin.site.register(Price)
admin.site.register(PaintColor)
admin.site.register(PatinaColor)
admin.site.register(Materials)
admin.site.register(Category)
admin.site.register(Products)

5. Register standard models:
#Регистрируем стандартные
admin.site.register(Group, GroupAdmin)
admin.site.register(User, UserAdmin)

And everything works as it should.
Thanks to all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question