longgb246的博客

Tutorial_7 Customizing the admin site

一、管理admin

1、修改顺序

1
2
3
4
5
6
7
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、修改标题

1
2
3
4
5
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]

使得显示的标题信息增加。

3、增加投票信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

使用内联式的会更好。

1
2
class ChoiceInline(admin.TabularInline):
#...

4、列表信息

1
2
3
class QuestionAdmin(admin.ModelAdmin):
# ...
list_display = ('question_text', 'pub_date', 'was_published_recently')

5、添加filter

models里添加。

1
2
3
4
5
6
7
8
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添加。

1
list_filter = ['pub_date']

6、添加搜索

admin里的QuestionAdmin添加。

1
search_fields = ['question_text']

二、建立app的admin

在app的templates文件夹下建立admin文件夹,将django/contrib/admin/templates/admin/base_site.html拷贝到templates/admin/下。
修改指定部分

1
2
3
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
{% endblock %}

坚持原创技术分享,您的支持将鼓励我继续创作!