6

I tried following an answer at this previous post: DateTimeField doesn't show in admin system

But maybe I'm just too dim to understand it.

No field of created_at shows up. Could anyone point me in the right direction?

model

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)   

Edit:

Community
  • 1
  • 1
vandelay
  • 1,965
  • 8
  • 35
  • 52

1 Answers1

9

Update:

Here is the code that worked for me for an imaginary application called Beatles:

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

beatles/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 to the question mentioned, states that this is not possible to happen.

Nonetheless, if you want to edit such fields, according to the docs you proceed as follows:

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()

If you want those fields just to be displayed, you can use the following code:

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

admin.site.register(YourModel, YourModelAdmin)
Community
  • 1
  • 1
raratiru
  • 8,748
  • 4
  • 73
  • 113
  • I just want them to be displayed. I tried your 2nd block, but was not succesful, are there anything else I need to do to apply it? – vandelay Sep 12 '16 at 19:35
  • You also need to add a fields option to PersonAdmin like so: fields = ('name', 'created_at') The readonly_fields option only makes specified fields read-only, it does not add them. – Sergei Krupenin Jun 09 '22 at 00:25