- admin site:django自带了admin site,我们需要创建能访问site的用户
#以交互的方式创建超级用户manage.py createsuperuser
- 如果要把model加到admin site,需要在polls/admin.py中执行如下命令:
from django.contrib import adminfrom polls.models import Question,Choiceadmin.site.register(Question) admin.site.register(Choice)
- 打开admin site的model,会有一个默认form显示model的成员,如果想自定义form可以使用如下代码:
#polls/admin.pyfrom django.contrib import adminfrom polls.models import Questionclass QuestionAdmin(admin.ModelAdmin): fields = ['pub_date', 'question_text']admin.site.register(Question, QuestionAdmin)
-
from django.contrib import adminfrom polls.models import Questionclass 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.pyfrom django.contrib import adminfrom polls.models import Choice, Questionclass 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)
#使ChoiceInline 继承自admin.TabularInline,其他代码不变class ChoiceInline(admin.TabularInline):...
- 还可以指定其他属性增加admin page的功能,如:
#指定model的列名,也就是属性名list_display = ('question_text', 'pub_date')#指定用于filter的列 list_filter = ['pub_date']#添加search box,使用question_text属性匹配 search_fields = ['question_text']
posted on 2014-09-23 13:51 阅读( ...) 评论( ...)