Jonathan1314

导航

Django Admin 专题

Django admin

Django强大的功能之一就是提供了Admin后台管理界面,简单配置就可以对数据库内容做管理

 

创建ModelAdmin并注册

from django.contrib import admin
from . import models

# version 1
admin.site.register(models.Author)

# version 2
class AuthorAdmin(admin.ModelAdmin):
    pass
admin.site.register(models.Author, AuthorAdmin)

# version 3
@admin.register(models.Author)
class AuthorAdmin(admin.ModelAdmin):
    pass

说明:

  • django启动时,会自动去app下寻找admin模块,生成后台页面
  • 自动根据model的Field类型设置Form类型

 

配置ModelAdmin

  • label名称,定义Model Field是指定verbose_name

  • 排除某些字段 exclude

  • 显示有些字段 fields

  • 搜索某列 search_fields

  • 添加日期标签过滤 date_hierarchy

  • 排序 ordering

  • 列表显示更多列 list_dispaly

# 当出现多个字段含义,list_display展示时
def display_book_authors(obj):
    return ','.join([author.first_name for author in obj.authors.all() ])

display_book_authors.short_description = 'Authors'  # 展示列明

@admin.register(models.Book)
class BookAdmin(admin.ModelAdmin):
    fields = ('title', 'authors', 'publisher')
    search_fields = ('title', 'authors')
    date_hierarchy = 'publication_date'
    ordering = ('-id', 'publication_date',)
    list_display = ['title', 'publisher', display_book_authors, 'publication_date']

 

 

配置Action

def make_book_pub_date_now(modeladmin, request,queryset):
    queryset.update(publication_date=datetime.datetime.now())

@admin.register(models.Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ['title', 'publisher', 'publication_date']
    actions = [make_book_pub_date_now]

 

 

posted on 2017-09-18 16:37  Jonathan1314  阅读(298)  评论(0编辑  收藏  举报