Customize the admin form
too easy to do sth!
Adding related objects
在创建question的时候直接创建choice,利用的就是外键!
from django.contrib import admin
from .models import Choice, Question
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
换一种风格
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 2
Customize the admin change list
多显示一些属性
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
('question text', {'fields': ['question_text'], 'classes': ['collapse']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
继续修改代码,给Question的was_published_recently
添加一些属性
class Question(models.Model):
# ...
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
在QuestionAdmin中添加以下两句,我想你能猜到会有什么效果!
list_filter = ['pub_date']
search_fields = ['question']
Customize the admin look and feel
Customizing your project’s templates
先创建一个templates目录
这样就把系统的模板的路径改变了,使模板再工程中是一个好的约定!
再在settings的TEMPLATES中添加一个DIRS路径,DIRS是加载django模板时要检查的文件系统列表,也就是搜索模板的路径列表!
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
接着再templates中建一个admin路径,把admin/base_site.html从django 的源代码中拷贝到这个路径中,代码改写如下
{% extends "admin/base.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('N site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}