django admin


Author: yifei / Created: June 7, 2017, 4:07 p.m. / Modified: June 7, 2017, 4:32 p.m. / Edit

Basics

./manage.py startapp APP_NAME would create an admin.py file, you should define your admin classes in that file.

./manage.py createsuperuser creates a user, so that you could login into the admin site at http://youdomain.com/admin

by default, the admin panel only contains user and group settings.

how to create your own admin

  1. subclass django.contrib.admin.ModelAdmin in admin.py
  2. customize this class
  3. register it to the admin site

subclass

Here is a basic example

from django.contrib import admin
from mysite.books.models import Publisher, Author, Book

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'email')
    search_fields = ('first_name', 'last_name')
    list_filter = ('publication_date',)

admin.site.register(Publisher)

customize

customize the admin class by change class attributes:

  1. list_display 控制列表页显示的属性, 其中可以包含 Model 的属性或者函数
  2. search_fields 表示搜索框会搜索的属性
  3. list_filter 表示的是在右边显示的过滤器
  4. fields 表示的是在每一个object的详情页显示的属性, 更复杂的可以用fieldset. 注意这里面的属性如果是函数的话, 必须包含在 readonly_fields 中.

每一个属性都是一个 tuple 或者 list, 以 list_display 为例

list_display

changes how the object is shown in the list view of the model. e.g. list_display = ('first_name', 'last_name').

list_display 中的元素可以是:

# example
class PersonAdmin(admin.ModelAdmin):
    list_display = ('upper_case_name',)

    def upper_case_name(self, obj):
        return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    upper_case_name.short_description = 'Name'

评论区