一、管理admin
1、修改顺序
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin)
使得pub_date
显示在question_text
前面。
2、修改标题
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
使得显示的标题信息增加。
3、增加投票信息
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):
#...
4、列表信息
class QuestionAdmin(admin.ModelAdmin):
# ...
list_display = ('question_text', 'pub_date', 'was_published_recently')
5、添加filter
models
里添加。
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?'
admin
里的QuestionAdmin
添加。
list_filter = ['pub_date']
6、添加搜索
admin
里的QuestionAdmin
添加。
search_fields = ['question_text']
二、建立app的admin
在app的templates
文件夹下建立admin
文件夹,将django/contrib/admin/templates/admin/base_site.html
拷贝到templates/admin/
下。
修改指定部分
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
{% endblock %}