管理界面的URL,帐号和密码在第一次输入syncdb时建立
http://127.0.0.1:8000/admin/
编辑polls/admin.py
from django.contrib import admin
from polls.models import Poll
admin.site.register(Poll)
#改变顺序
from django.contrib import admin
from polls.models import Poll
class PollAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question']
admin.site.register(Poll, PollAdmin)
#添加域框,classes的值collapse表示默认紧缩
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
再添加poll的时候添加choice,而不是将choice做为单独一项进行添加
TabularInline和StackedInline对应,是做为表格的紧致表现形式。
from django.contrib import admin
from polls.models import Choice, Poll
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Poll, PollAdmin)
不仅能显示列,还能显示成员函数的值,但是成员函数的值是无法排序的。
class PollAdmin(admin.ModelAdmin):
# ...
list_display = ('question', 'pub_date', 'was_published_recently')
如下可设置成员函数的显示名称,以及按哪一可排序属性排序
class Poll(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
添加过滤与搜索功能
list_filter = ['pub_date']
search_fields = ['question']
项目、应用模版的位置可在settings中做相应设置。
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
默认的模版文件位于django的库目录(django/contrib/admin/template
s),可用如下命令查找django的目录。
python -c "
import sys
sys.path = sys.path[1:]
import django
print(django.__path__)"
项目的默认模版为admin/base_site.html,主页的模版为admin/index.html,复制到自己的模版目录后修改即可。