Yuqing  Wei
Yuqing Wei

Reputation: 309

How to show Django timestamp in backend

I'm using Django 1.6 as backend, what I want to do is to let users write their comments while watching the video. I wrote the field

datetime = models.DateTimeField(auto_now_add=True)

in the model.py, but in the Django back-end, I didn't see this column, how can I let it show in my admin? Thanks!

Upvotes: 2

Views: 2406

Answers (2)

Gokhan Sari
Gokhan Sari

Reputation: 7924

You can set a field of a model to be shown in admin by adding it to the ModelAdmin (in admin.py of the model's app):

from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('datetime',)

admin.site.register(MyModel, MyModelAdmin)

And to set the short description that is displayed next to the field, you need to set verbose_name of the field, like the following (in models.py):

class MyModel(models.Model):
    datetime = models.DateTimeField(auto_now_add=True, verbose_name="Uploaded at")

Note: You don't need to set readonly_fields since DateTimeField with auto_now_add=True arg will be read-only by default.

Upvotes: 3

ozren1983
ozren1983

Reputation: 1951

Just add readonly_fields option to you admin.py:

class CommentAdmin(admin.ModelAdmin):
    readonly_fields = ('datetime',)

If you have fields option defined in you admin class, you'll also have to add datetime to the fields option:

class CommentAdmin(admin.ModelAdmin):
    # display datetime in the changelist
    list_display = ('id', 'title', 'datetime')
    # display datetime when you edit comments
    readonly_fields = ('datetime',)
    # optional, use only if you need custom ordering of the fields
    fields = ('title', 'body', 'datetime')

admin.site.register(Comment, CommentAdmin)

For more info, please see: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

Upvotes: 5

Related Questions