一、准备工作

  1.创建应用

python manage.py startapp test

  2.定义模型类

    (1)打开刚创建的app目录test,打开models.py文件

    (2)代码如下

from django.db import models

class classes(models.Model):
    name = models.CharFild(max_length=32)

class student(models.Model):
    name = models.CharField(max_length=32)
    sex = models.BooleanField()
    class_name = models.ForeignKey(classes, on_delete=models.CASCADE)

    (3)激活模型:编辑settings.py文件,将test应用加入到installed_apps中

    (4)生成迁移文件:

python manage.py makemigrations

    (5)执行迁移:

python manage.py migrate

  3.生成后台:

    (1)创建管理员用户:

python manage.py createsuperuser

    (2)管理界面本地化:

编辑settings.py文件,设置编码、时区
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'

    (3)向admin注册模型

#打开test/admin.py文件,注册模型
from django.contrib import admin

from .models import *
admin.site.register(BookInfo, BookInfoAdmin)
admin.site.reigster(HeroInfo)

#class HeroInfoInline(admin.StackedInline):         # 正常表单
class HeroInfoInline(admin.TabularInline):          # 表格添加多个关联
    model = HeroInfo
    extra = 3

class BookInfoAdmin(admin.ModelAdmin):
    list_display = ['id', 'btitle', 'bpub_date']    # 列表显示数据
    list_filter = ['btitle']                        # 过滤字段
    search_fields = ['btitle']                      # 搜索字段
    list_per_page = 1                               # 每页条数
    #fields = ['bpub_date', 'btitle']                # 添加修改页字段顺序
    fieldsets = [                                   # 添加列表分组
        ('base', {'fields':['btitle']}),
        ('super', {'fields':['bpub_date']})
    ]
    inlines = [HeroInfoInline]                      # 关联添加