Django develops the display mode of the model

The following is mainly related to the way to customize the management site. In this regard, you can edit the admin.py file of the XX application (here I take blog as an example) and modify it as follows:

from django.contrib import admin
from .models impot Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
     list_display = ('title', 'slug', 'author', 'publish', 'status')

Here, we will notify the Django management site that the current model is registered in the management site through a custom class inherited from ModelAdmin. This class can contain information related to the way the model is displayed and how it interacts in the management site. Correspondingly, the list_display attribute can set the model field that you want to display in the management object list page; the @admin.register() decorator performs the same function as the admin.site.register() function we have replaced, and registers its decoration The ModelAdmin class.

The following uses more options to customize the management model, and the corresponding code is as follows:

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'author', 'publish', 'status')
    list_filter = ('status', 'created', 'publish', 'author')  # 右侧栏
    search_fields = ('title', 'body')  # 搜索栏
    prepopulated_fields = {
    
    'slug': ('title',)}  # 根据输入的title字段预填充slug字段
    raw_id_fields = ('author',)  # author字段利用搜索微键予以展示
    date_hierarchy = 'publish'   # 导航链接
    ordering = ('status', 'publish')  # 按照 status 和 publish 排序

Return to the browser and reload the post list page, the corresponding results are as follows:

Insert picture description here
It is not difficult to find that the fields displayed on the post list page are actually the fields specified in the list_display attribute. The list page contains the right column, and the results are filtered by the fields contained in the list_filter attribute.

In summary, it only takes a few lines of code to customize the way the model is displayed on the management site. In addition, there are many ways to customize and extend the Django management site.

Through the above points, I hope to give you some inspiration, thank you for your support.

Guess you like

Origin blog.csdn.net/Erudite_x/article/details/112533600