1. 定制admin后台

1.1 设置模型str

在某个app目录下的models.py中添加类中函数

  1. def __str__(self):
  2. return <"A_tea: %s"> % self.tile
  3. 其中字段中<>不能与app名同名
  4. 例如app Teamodels.py __str__中返回的标题字段不能设为<"Tea: %s">

1.2 定制admin

然后在app下的admin.py中定制类

  1. #coding=gbk
  2. from django.contrib import admin
  3. from .models import firstTea
  4. # Register your models here.
  5. #装饰器 可在每个类前使用进行注册
  6. #替代 后面进行统一注册
  7. @admin.register(firstTea)
  8. class TeaAdmin(admin.ModelAdmin):
  9. #模型定制类
  10. list_display = ("id", "title", "content")
  11. #排序规则 可按不同字段定制
  12. # ordering = ("-id",)#倒序排序 默认
  13. ordering = ("id",)#顺序排序
  14. # admin.site.register(firstTea, TeaAdmin)

5 定制后台和修改模型 - 图1

报错:

(admin.E108) The value of 'list_display[0]' refers to 'id'
id为自动生成的主键pk,在migrations下的0001_initial.py中查看生成的字段数与字段名。修改缩进或编码格式可解决错误

2. 修改模型

修改模型后要更新数据库

python manage.py makemigrations

python manage.py migration

需要设置默认值


首先对原数据库备份 db_copy.sqlite3。
在models.py中添加字段

 #生产日期
create_date = models.DateTimeField()

刷新界面报错

5 定制后台和修改模型 - 图2

因为数据库没有同步添加字段

django.db.utils.OperationalError: no such column: Tea_firsttea.create_date

进行数据库同步

python manage.py makemigrations
提示错误
You are trying to add a non-nullable field 'create_date' to firsttea without a default; we can't do that (the database needs something to populate existing rows).

Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
原因没有为字段填充默认值

2.1 方法一:填充默认值

命令行输入 1
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
默认时间为格林尼治时区,可在全局setting中设置TIME_ZONE字段参数为Asia/Shanghai
>>> timezone.now
Migrations for 'Tea':
Tea\migrations\0002_firsttea_create_date.py
- Add field create_date to firsttea
python manage.py migrate

最后在admin中list_display可以添加create_date

2.2 方法二:直接设置默认值

    create_date = models.DateTimeField(auto_now_add=True)#新增时自动添加现在时间
#自动用现在时间赋值最新更改
last_updated_time = models.DateTimeField(auto_now=True)
admin中list_display同样添加字段

添加作者字段author,同时修改admin.py

author = models.ForeignKey(User,on_delete=models.DO_NOTHING,default=1)

添加is_deleted字段,同时修改admin.py

#标识是否真正从库中删除
is_deleted = models.BooleanField(default=False)

添加click_num字段(未生效),同时修改admin.py

#点击数
click_count = models.IntegerField(default=0)

添加删除操作后都需要进行

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

is_deleted可用于设计views.py中的筛选显示


def tea_list(request):
    # teas = firstTea.objects.all()
    teas = firstTea.objects.filter(is_deleted=False)
    context = {}
    context['teas'] = teas
    return render(request,'tea_list.html',context)