Search code examples
pythondjangodjango-modelsdjango-admindjango-admin-filters

How to display only date from datetime field in modelAdmin in Django admin panel?


I have a model which has a column created_at which is actually a datetime field of this format 16.07.2019 12:26:37.

I want to display only date present in this created_at field in admin panel in Django.

I can display the whole field's value which is datetime if I mention the 'created_at' in list_display while creating modelAdmin.

How can I display only the date value in results page like this 16.07.2019?

Are there any inbuilt filters to do that while registering the modelAdmin?

Python: 3.7.3
Django: 2.1.5

Solution

  • You can add a method to the ModelAdmin class.

    @admin.register(YourModel)
    class YourModelAdmin(admin.ModelAdmin):
        list_display = ('get_date_formatted',)
    
        def get_date_formatted(self, obj):
            if obj:
                return obj.date.date()
        get_date_formatted.admin_order_field = 'date'
        get_date_formatted.short_description = 'date'