Django基础,Day8 - 管理后台定制显示

时间:2023-03-08 16:57:30

自定义admin表单

展示效果一:

Django基础,Day8 - 管理后台定制显示

 from django.contrib import admin
from polls.models import Question class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text'] admin.site.register(Question, QuestionAdmin)

polls/admin.py

展示效果二:

Django基础,Day8 - 管理后台定制显示

 from django.contrib import admin
from polls.models import Question class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
] admin.site.register(Question, QuestionAdmin)

polls/admin.py

添加关联对象

一个Question有多个Choice,Choice的显示方式有两种:

其一,直接注册 admin.site.register(Choice),则Choice添加界面显示如:

Django基础,Day8 - 管理后台定制显示

其二,在Question中关联Choice,效果展示如:

Django基础,Day8 - 管理后台定制显示

 from django.contrib import admin
from polls.models import Question, Choice class ChoiceInline(admin.TabularInline): # admin.TabularInline admin.StackedInline
model = Choice
extra = 0 class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin)

polls/admin.py

自定义admin列表

增加显示列    list_display = ('question_text', 'pub_date', 'was_published_recently')

增加过滤器    list_filter = ['pub_date']

添加搜索栏    search_fields = ['question_text']

Django基础,Day8 - 管理后台定制显示

 from django.contrib import admin
from polls.models import Question, Choice class ChoiceInline(admin.TabularInline): # admin.TabularInline admin.StackedInline
model = Choice
extra = 0 class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)

polls/admin.py


Django基础,Day8 - 管理后台定制显示

***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***