Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying display format of DateTimes in django-tables2

I'm currently using django-tables2 to display a queryset of my model. One of the attributes of this model is a DateTimeField accurate to the millisecond which is being truncated to the minute in my table.

I had previously manually implemented a simple table in HTML and had no issues. My DateTimeFields were following true to the DATETIME_FORMAT applied in my settings:

settings.py

DATETIME_FORMAT = 'Y N j, H:i:s.u'

The problem has arisen since I began using django-tables2. Is there some way to modify the way it displays DateTimeFields or make it follow my specified DATETIME_FORMAT? I need to retain the sorting functionality so converting to a string is not an option.

I'm using render_table to display my table. The following is my table class:

class ModelTable(tables.Table):
    class Meta:
        model = Measurement
        sequence = ('date_time', 'latitude', 'longitude',
                    'depth', 'soundvel', 'instrument')
like image 260
Scott Quinton Avatar asked Jan 20 '15 15:01

Scott Quinton


2 Answers

Problem solved.

django-table2's DateTimeColumn class seems to be looking for a SHORT_DATETIME_FORMAT rather than the DATETIME_FORMAT in my settings.py. Updated the value in my settings file and everything is in working order.

like image 115
Scott Quinton Avatar answered Sep 29 '22 09:09

Scott Quinton


This confused me for a while as I tried to use the Python datetime formatting options. The formatting options for Django templates apply in django-tables2, and are fully enumerated at the Django docs:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatefilter-date

From that, if you have a model with one datetime column, and you want their birthday to be formatted as Month Day Year, Hour:Minute AM/PM, then you would enter the following:

class MyTable(tables.Table):
    birthday = tables.DateTimeColumn(format ='M d Y, h:i A')

    class Meta:
        model = Person
        attrs = {'class': 'table'} 
        fields =  ['birthday']
like image 41
eric Avatar answered Sep 29 '22 07:09

eric