Format DateTime in Django Admin

Posted: March 10th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: , | 6 Comments »

If you are trying to format a DateTimeField() field in the Django admin you may find it harder than you think. You would think that the DATE_FORMAT and DATETIME_FORMAT in settings.py would apply to the admin BUT it only applies to date formatting in the template.

At present there is no easy way to format the date but the following example of one method of how to do it:

class News(models.Model):
    headline = models.CharField(max_length=100)
    date = models.DateTimeField()
    article = models.TextField()
    published = models.BooleanField()

class NewsAdmin(admin.ModelAdmin):
    list_display = ('headline', 'format_date', 'published')

    def format_date(self, obj):
        return obj.date.strftime('%d %b %Y %H:%M')
    format_date.short_description = 'Date'

6 Comments on “Format DateTime in Django Admin”

  1. 1 Marek Zakowicz said at 12:14 pm on September 15th, 2010:

    Unfortunatly, in above solution, we can not sort lists using redefined field (‘format_date’)

  2. 2 Mitja said at 6:04 pm on November 4th, 2010:

    You can preserve sorting by adding this line:

    format_date.admin_order_field = ‘date’

  3. 3 Mitja said at 6:12 pm on November 4th, 2010:

    … and moving format_date function to the model …

  4. 4 josiano said at 10:45 am on November 13th, 2010:

    yes you can:

    format_date.admin_order_field = ‘date’

  5. 5 Maciej 'barszcz' Marczewski said at 2:04 pm on November 23rd, 2010:

    Yes we can sort list using this field. All we have to do is to write:
    format_date.admin_order_field = ‘date’

  6. 6 Basil Shubin said at 6:04 am on November 26th, 2010:

    Just add – format_date.admin_order_field = ‘date’ beyond – format_date.short_description to fix list sorting.


Leave a Reply