本教程从 第 6 个教程 结束的地方开始。我们将继续开发 web-poll 应用程序,并专注于自定义 Django 自动生成的管理网站,这一点我们在 第 2 个教程 中首次进行了探索。
自定义管理表单
在 polls/admin.py 中修改:
from django.contrib import admin
from .models import Questionclass QuestionAdmin(admin.ModelAdmin):fields = ["pub_date", "question_text"]
admin.site.register(Question, QuestionAdmin)
如图:
上述特定的更改使得“出版日期”字段出现在“问题”字段之前
启动服务器
bash python manage.py runserver
访问 http://127.0.0.1:8000/admin/polls/question/1/change/ :
继续修改:
from django.contrib import admin
from .models import Questionclass QuestionAdmin(admin.ModelAdmin):fieldsets = [(None, {"fields": ["question_text"]}),("Date information", {"fields": ["pub_date"]}),]
admin.site.register(Question, QuestionAdmin)
结果显示:
每个元组中 fieldsets 的第一个元素是字段集的标题。
添加相关对象
第一种方式:
注册 Choice
from django.contrib import admin
from .models import Choice, Question
# ...
admin.site.register(Choice)
访问 http://127.0.0.1:8000/admin/polls/choice/add/
结果如图:
第二种方式:
修改代码:
from django.contrib import admin
from .models import Choice, Questionclass ChoiceInline(admin.StackedInline):model = Choiceextra = 3
class QuestionAdmin(admin.ModelAdmin):fieldsets = [(None, {"fields": ["question_text"]}),("Date information", {"fields": ["pub_date"], "classes": ["collapse"]}),]inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
再次访问http://127.0.0.1:8000/admin/polls/question/1/change/:
进一步优化:
from django.contrib import admin
from .models import Choice, Questionclass ChoiceInline(admin.TabularInline):model = Choiceextra = 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 QuestionAdmin(admin.ModelAdmin):# ...list_display = ["question_text", "pub_date", "was_published_recently"]
访问:http://127.0.0.1:8000/admin/polls/question/
修改前后变化:
在polls/models.py中添加代码:
from django.contrib import admin
class Question(models.Model):# ...@admin.display(boolean=True,ordering="pub_date",description="Published recently?",)def was_published_recently(self):now = timezone.now()return now - datetime.timedelta(days=1) <= self.pub_date <= now
在polls/models.py中添加代码:
list_filter = ["pub_date"]
结果:
添加search框,在polls/models.py中添加代码:
search_fields = ["question_text"]