[Django]-Django admin, setting a non-editable date field on creation with the DateTime widget

5👍

I am a novice in this area, but the code that I have in front of me has the following idiom, in admin.py:

class ThingAdmin(admin.ModelAdmin):

    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ('start',)
        else:
            return ()

In my example, this has the effect of leaving it editable when creating a new object, but not when looking at an old object.

👤jjc

0👍

This is how I’d do it.

in ‘models.py’:

class Thing(models.Model):
    #field 1
    .....
    date = models.DateTimeField(auto_now_add=True)

in admin.py:

class ThingAdmin(admin.ModelAdmin):
    list_display = (....., 'date')

Leave a comment