我尝试在上一篇文章中回答: 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)
编辑:
答案 0 :(得分:4)
更新
以下代码适用于名为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进行操作,如下所示:
如果您希望能够修改此字段,请改为设置以下内容 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)