修改polls/admin.py
from django.contrib import admin
from .models import Question, Choice
# Register your models here.
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
# Choice对象要在Question后台页面编辑,默认提供3个足够的选项字段
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('日期信息', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)
# 创建一个模型后台类,接着将其作为第二个参数传给admin.site.register()
修改polls/models.py
import datetime
from django.utils import timezone
from django.db import models
# Create your models here.
# 在我们的polls应用程序中,
# 将创建两个模型:Question和Choice,
# Question有一个问题和一个出版日期,
# Choice有两个领域:选择的文本和票数,
# 每个Choice都关联一个Question
class Question(models.Model):
question_text = models.CharField(max_length=200, verbose_name='问题文本')
pub_date = models.DateTimeField('出版日期')
def __str__(self):
return self.question_text
class Meta:
verbose_name = '问题'
verbose_name_plural = '问题'
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 = '最近发布?'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200, verbose_name='选择文本')
votes = models.IntegerField(default=0, verbose_name='选票')
def __str__(self):
return self.choice_text
class Meta:
verbose_name = '选择'
verbose_name_plural = '选择'
python manage.py runserver
启动服务