- admin site:django自带了admin site,我们需要创建能访问site的用户
#以交互的方式创建超级用户 manage.py createsuperuser
- 如果要把model加到admin site,需要在polls/admin.py中执行如下命令:
from django.contrib import admin from polls.models import Question,Choice admin.site.register(Question)
admin.site.register(Choice) - 打开admin site的model,会有一个默认form显示model的成员,
如果想自定义form可以使用如下代码:#polls/admin.py from django.contrib import admin from polls.models import Question class QuestionAdmin(admin.ModelAdmin): fields = ['pub_date', 'question_text'] admin.site.register(Question, QuestionAdmin)
如果有许多fields,可以将form按field set进行划分,collapse指定这个fieldset初始是收缩的,点show可以展开,如下图Text是一个fieldset,Date information是一个fieldset -
from django.contrib import admin from polls.models import Question class QuestionAdmin(admin.ModelAdmin): fieldsets = [ ('Text', {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ]
- 添加关联对象,如下图,
django知道ForeignKey对象应该从select box中选择,本例中时选择Question model,如果想连续添加多个Choice对象,可以更改admin.py代码,#polls/admin.py from django.contrib import admin from polls.models import Choice, Question class ChoiceInline(admin.StackedInline): model = Choice #extra 是添加的数目 extra = 3
class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ]
#这告诉django,Choice model在Question的admin page编辑,添加3个Choice对象
inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin)
可以点”Add another Choice”继续添加Choice,新添加的Choice可以删掉,但初始的3个slot不能删。为了节省空间可以使用下列显示方式: - 还可以指定其他属性增加admin page的功能,如:
#指定model的列名,也就是属性名 list_display = ('question_text', 'pub_date') #指定用于filter的列 list_filter = ['pub_date'] #添加search box,使用question_text属性匹配 search_fields = ['question_text']