gpt4 book ai didi

django - 管理面板,显示创建日期和更新日期?

转载 作者:行者123 更新时间:2023-12-01 22:10:12 26 4
gpt4 key购买 nike

我尝试遵循上一篇文章中的答案: DateTimeField doesn't show in admin system

但也许我太愚钝了,无法理解它。

没有显示created_at字段。有人能指出我正确的方向吗?

型号

class holding_transaction(models.Model):
holdingname = models.ForeignKey(holding, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

admin.py

class holding_transactionAdmin(admin.ModelAdmin):

readonly_fields = ('created_at', )

admin.site.register(holding_transaction, holding_transactionAdmin)

编辑:

最佳答案

更新:

以下代码适用于我的一个名为 Beatles 的虚构应用程序:

披头士/models.py:

from django.db import models

# Create your models here.

class Person(models.Model):
name = models.CharField(max_length=128)
created_at = models.DateTimeField(auto_now_add=True)


def __str__(self): # __unicode__ on Python 2
return self.name

披头士/admin.py

from django.contrib import admin

# Register your models here.

from beatles.models import Person


@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
readonly_fields = ('created_at', )
<小时/>

The answer对于提到的问题,指出这是不可能发生的。

尽管如此,如果您想编辑此类字段,请按照the docs您按照以下步骤操作:

If you want to be able to modify this field, set the following instead of auto_now_add=True:

For DateField: default=date.today - from datetime.date.today()
For DateTimeField: default=timezone.now - from django.utils.timezone.now()

如果您只想显示这些字段,可以使用 following code :

class YourModelAdmin(admin.ModelAdmin):
readonly_fields = ('created_at', 'updated_at', )

admin.site.register(YourModel, YourModelAdmin)

关于django - 管理面板,显示创建日期和更新日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39455574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com