django admin中,显示auto型的DateTimeFi

2021-01-24  本文已影响0人  万州客

显示情况下,在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)

二,在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)

四,原理说法
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.
`

上一篇 下一篇

猜你喜欢

热点阅读