目录
- 模型
- 注册模型
- 定制页面
模型
# app/model.py
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now()- datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
注册模型
1.admin.site.register
# app/admin.py
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text'] # 字段顺序=界面上字段展示顺序,可随意调整
admin.site.register(Question, QuestionAdmin)
2.装饰器写法
# app/admin.py
from django.contrib import admin
from .models import Question
@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
定制页面
基础定制
# app/admin.py
from django.contrib import admin
from .models import Choice, Question
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3 # 提供3个Choice对象编辑区域
class QuestionAdmin(admin.ModelAdmin):
# Question列表页面显示的内容
list_display = ('pk', 'question_text', 'pub_date', 'was_published_recently')
# 点击可跳转
list_display_links = ('pk', 'pub_date',)
# 列表界面可编辑
list_editable = ["question_text"]
# 划分字段集合
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
# 在Question页面编辑Choice对象
inlines = [ChoiceInline]
# 过滤器
list_filter = ['pub_date']
# 搜索功能
search_fields = ['question_text']
# 按id降序排列
ordering = ('-pk',)
admin.site.register(Question, QuestionAdmin)
改进模型方法的输出样式
# app/model.py
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页面顶端Django administratione文本
from django.contrib import admin
admin.site.site_header = 'Q&A管理系统'
admin日期字段格式化
1.单独更新某时间字段
# app/admin.py
list_display = (..., 'simple_pub_date', ...)
def simple_pub_date(self, obj):
return obj.pub_date.strftime"%Y-%m-%d %H:%M:%S")
simple_pub_date.short_description="发布时间"
2.整个系统的时间格式都使用同一种日期格式,配置settings.py文件
# mysite/settings.py
USE_L10N = False
DATETIME_FORMAT = "Y-m-d H:i:sO"
date_format = 'Y-m-d'