django 后台日期_django admin中,显示auto型的DateTimeField字段

本文介绍了在Django admin后台如何显示自动更新的DateTimeField字段。通过在model中定义,并在admin.py中配置readonly_fields,可以使得create_date和update_date在后台管理界面中可见。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

显示情况下,在django admin后台,具有自动更新的日期字段,是不会显示在后台的。那如何显示出来呢?

一,django model中的定义

class BaseModel(models.Model):

name = models.CharField(max_length=100,

unique=True,

verbose_name="名称")

description = models.CharField(max_length=100,

null=True,

blank=True,

verbose_name="描述")

create_user = models.ForeignKey(User,

blank=True,

null=True,

on_delete=models.SET_NULL,

verbose_name="用户")

update_date = models.DateTimeField(auto_now=True)

create_date = models.DateTimeField(auto_now_add=True)

base_status = models.BooleanField(default=True)

history = HistoricalRecords(inherit=True)

create_date 会在第一次增加时记录日期,

update_date 会在每一次更新时,自动更新日期(有条件调用语句)。

这两个字段,默认情况,不会在django admin后台管理界面上显示。

二,在admin.py中增加配置

class ReleaseHistoryHistoryAdmin(SimpleHistoryAdmin):

list_display = ['id', 'name', 'release', 'env', 'deploy_status', 'deploy_type', 'log']

history_list_display = ["status"]

search_fields = ['name', 'release', 'log']

readonly_fields = ('create_date', 'update_date')

admin.site.register(ReleaseHistory, ReleaseHistoryHistoryAdmin)

readonly_fields的配置是关键,因为自动日期具有不可编辑的内在属性。

三,此时方可显示

dfff2d9f7522

2021-01-24 09_04_28-悬浮球.png

四,原理说法

https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield

`

As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set.

The auto_now and auto_now_add options will always use the date in the default timezone at the moment of creation or update. If you need something different, you may want to consider using your own callable default or overriding save() instead of using auto_now or auto_now_add; or using a DateTimeField instead of a DateField and deciding how to handle the conversion from datetime to date at display time.

`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值