[PYTHON] [Django] Want to customize your admin page?

Introduction

For those who say, "I've never customized the Django admin page." This is a beginner's edition.

It seems that it can be used without customization, but when people other than engineers touch it, is it a little lonely by default?

Rather than a detailed explanation, it is a style that raises good terms quickly when you google. It's hard to put it together properly. .. ..

Django documentation https://docs.djangoproject.com/en/3.0/ref/contrib/admin/

ModelAdmin class

Basically, create a subclass of the ModelAdmin class and describe the customization contents. For example, if you want to customize a model named SampleModel, do the following:

admin.py



from django.contrib import admin

#Normally, name it "model name + Admin"
class SampleModelAdmin(admin.ModelAdmin):
    '''
Describe the customization contents in this class
    '''

#Apply SampleModelAdmin to SampleModel
admin.site.register(SampleModel, SampleModelAdmin)

From this point onward, write only the description in the ModelAdmin class. For example


def hoge():
    return

If you write, in fact

admin.py


class SampleModelAdmin(admin.ModelAdmin):
    def hoge():
        return

Please read as.

What column to display

スクリーンショット 2020-08-08 20.38.22.png

The column name is displayed at the top of the record list, but let's set what column you want to display. The following is an example when the model has fields called text and updated_at.

list_display = ('__str__', 'text', 'updated_at')  #Display these three columns

Next, if you want to display a value that is not in the field.

list_display = ('__str__', 'text', 'updated_at', 'get_owner_name')

def get_owner_name(self, obj):
    #The second argument obj represents the record itself
    return "I am owner"
get_owner_name.short_description = 'Owner name'

This will add a column called "Owner Name", which will display "I am owner" on all records.

Set the search target

スクリーンショット 2020-08-08 21.08.22のコピー.png

There is a search box at the top, but you can narrow down the search target.

# SampleModel.text, SampleModel.updated_at, SampleModel.owner.Search for username
search_fields = ('text', 'updated_at', 'owner__username`)

Add an operation

スクリーンショット 2020-08-08 21.32.13のコピー.png

By default, there should be an operation called "Delete selected ". The self-made action is described in ʻactions` in list format as follows, but "Delete selected " continues to exist even if it is not explicitly included here.

actions = ['my_custom_action']

def my_custom_action(self, request, queryset):
    #Something processing
    return None
my_custom_action.short_description = 'Action only for me'

If you set return None, nothing will be done when the operation is completed, but for example, you can return a template and perform page transitions.

Change the display name of the model

スクリーンショット 2020-08-08 21.32.13.png

Write this in the original Model class instead of ModelAdmin.


class SampleModel(models.Model):
     class Meta:
         verbose_name = 'Sample model'
         verbose_name_plural = 'List of sample models'

Do you want to put a link in the field


list_display_links = ('text',)

Advanced: Customize search process

We have introduced the customization of the search target, but you can also customize what kind of search is actually performed when a search word (query) is given. This will be lengthy, so I'll just give you an overview, but define the following function to override the search process.


def get_changelist(self, request, **kwargs):

Finally

If you can customize the above, wouldn't you be satisfied at first? I will write about customizing the admin page template itself and page transitions within admi in another article.

Recommended Posts

[Django] Want to customize your admin page?
Tuning your Django admin site
I can't log in to the admin page with Django3
Django non-logged-in users want to transition to login.html
[Python] Introduce UIKit3 to your Django project
Want to add type hints to your Python decorator?
Django tutorial summary for beginners by beginners ⑦ (Customize Admin)
I want to pin Datetime.now in Django tests
I want to customize the appearance of zabbix
Customize the model page on Django's admin screen
I want to upload a Django app to heroku
Python beginners try adding basic auth to Django admin
I want to scroll the Django shift table, but ...
Steps from installing Django to displaying an html page
TemplateView patterns you'll want to learn first in Django
When you want to filter with Django REST framework
Single sign-on to your Django application with AWS SSO
[Django] How to redirect unlogged-in users to the login page
Initialize your Django app
unable to import django
update django version 1.11.1 to 2.2
[Django] A memorandum when you want to communicate asynchronously [Python3]
[Django] I want to log in automatically after new registration
If you want your colleagues to use the same language
When you forget your admin screen username / password in Django
[Django] Redirect to previous page after submitting with POST form