victory的博客

长安一片月,万户捣衣声

0%

Django | django自定义后台表单

django自定义后台表单的显示方式。

以问题投票为例说明后台表单的自定义:

1.准备所需的模型类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import datetime

from django.db import models
from django.utils import timezone
from django.contrib import admin


# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")

def __str__(self):
return self.question_text

# 定制布尔值字段的显式方式
@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


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

2.自定义后台表单的显式方式

django后台访问:ip:port/admin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from django.contrib import admin  # 导入django内置模型管理类
from .models import Question, Choice # 导入自定义模型类


class ChoiceInline(admin.TabularInline):
# admin.TabularInline: 单行显示关联对象
# admin.StackedInline: 多行显示关联对象
model = Choice
extra = 3


# 定义后台Question表单
class QuestionAdmin(admin.ModelAdmin):
# 定义属性显式顺序
# fields = ["pub_date", "question_text"]

# 将模型类的属性划分成不同的信息区域,适用于模型类有多个属性且存在同类型属性
fieldsets = [
(None, {"fields": ["question_text"]}),
("Date information", {"fields": ["pub_date"]}),
]

# 修改列表页中列表项的显式信息
list_display = ["question_text", "pub_date", "was_published_recently"]

# 增加过滤器
list_filter = ["pub_date"]

# 增加搜索框
search_fields = ["question_text"]

# 分页,一页展示5个列表项
list_per_page = 5

# 添加关联的对象
inlines = [ChoiceInline]


# 定义后台Choice表单
class ChoiceAdmin(admin.ModelAdmin):
fieldsets = [
("Question Information", {"fields": ["question"]}),
("Seletions Information", {"fields": ["choice_text"]}),
("Voting Information", {"fields": ["votes"]}),
]

# 增加搜索框
search_fields = ["choice_text"]

# 增加过滤器
list_filter = ["votes"]

# 列表项展示内容
list_display = ["choice_text", "votes"]

# 分页,一页展示5个列表项
list_per_page = 5

# 字段(选项投票数)可编辑
list_editable = ["votes"]

# 将模型类注册到后台中进行管理
admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice, ChoiceAdmin)