Modifying display format of DateTimes in django-tables2
Asked Answered
D

3

8

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')
Dowse answered 20/1, 2015 at 15:22 Comment(0)
D
9

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.

Dowse answered 20/1, 2015 at 15:59 Comment(1)
works as described in django-tables2 version 2.4.1 in django version 4.0.3Teteak
F
8

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']
Fabled answered 16/2, 2018 at 15:35 Comment(0)
J
0

You can add 'format' as argument to DateTimeColumn.

https://django-tables2.readthedocs.io/en/latest/_modules/django_tables2/columns/datetimecolumn.html

class DateTimeColumn(TemplateColumn):
    """
    A column that renders `datetime` instances in the local timezone.

    Arguments:
        format (str): format string for datetime (optional).
                      Note that *format* uses Django's `date` template tag syntax.
        short (bool): if `format` is not specified, use Django's
                      ``SHORT_DATETIME_FORMAT``, else ``DATETIME_FORMAT``
Jorrie answered 25/10, 2018 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.