Django -- Polls - Part 7

定制 Django Admin

# 类
admin.ModelAdmin
admin.StackedInine
admin.TabularInline

# Model Edit Form
## ModelAdmin
fields = []
fieldsets = [('title', {'fields': [])]
inlines
## Change List
search_fields
list_display
list_filter
# Inline 属性
model 
extra

# 方法属性
field.admin_order_filed # 排序
field.boolean
field.short_description # 标题

步骤:

  • 创建 admin.ModelAdmin
  • 将子类作为 admin.site.register() 的第二个参数

Model

Model 中 Fields 显示的顺序:fields

# polls/admin.py

from django.contrib import admin
from .models import Question

class QuestionAdmin(admin.ModelAdmin):
    fields = ['pub_date', 'question_text']

admin.site.register(Question, QuestionAdmin)

fieldsets:

# polls/admin.py
class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
    ('Date information', {'fields': ['pub_date']}), # ('title', {'fileds': []})
    (None, {'fields': ['question_text']}),
    ]
Django -- Polls - Part 7_第1张图片
fieldsets

关联外键

Inline

# polls/admin.py

from django.contrib import admin
from .models import Question, Choice

class ChoiceInline(admin.StackedInline):
    model = Choice
    extra = 3

class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
    ('Date information', {'fields': ['pub_date']}), # (title, {'fileds': []})
    (None, {'fields': ['question_text']}),
    ]

    inlines = [ChoiceInline]

admin.site.register(Question, QuestionAdmin)

紧凑的表格形式 TabularInline

# polls/admin.py
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3
Django -- Polls - Part 7_第2张图片
TabularInine

Change List

# polls/admin.py
class QuestionAdmin(admin.ModelAdmin):
    list_display = ('question_text', 'pub_date', 'was_published_recently')
Django -- Polls - Part 7_第3张图片
list_display
Model

was_published_recently 添加属性

# polls/models.py
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
         return timezone.now() - self.pub_date < datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = "Published recently ?"
Django -- Polls - Part 7_第4张图片
属性

list_filter

class QuestionAdmin(admin.ModelAdmin):
    list_filter = ['pub_date']

search_fields

class QuestionAdmin(admin.ModelAdmin):
    search_fields = ['question_text']  # 在数据库执行 LIKE
Django -- Polls - Part 7_第5张图片
  • list_display
  • list_filter
  • Change list pagination`,
  • search boxes,
  • filters
  • column-header-ordering

你可能感兴趣的:(Django -- Polls - Part 7)