Format DateTime in Django Admin
Posted: March 10th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: datetime, format | 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'

Unfortunatly, in above solution, we can not sort lists using redefined field (‘format_date’)
You can preserve sorting by adding this line:
format_date.admin_order_field = ‘date’
… and moving format_date function to the model …
yes you can:
format_date.admin_order_field = ‘date’
Yes we can sort list using this field. All we have to do is to write:
format_date.admin_order_field = ‘date’
Just add – format_date.admin_order_field = ‘date’ beyond – format_date.short_description to fix list sorting.