自定义admin表单
展示效果一:
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
展示效果二:
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添加界面显示如:
其二,在Question中关联Choice,效果展示如:
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']
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
***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***