1

I'm currently working on a project using Django 1.11.2 with django-tables2. I use a table to display my model. The model has a DateTimeField, which is displayed correctly in a normal column but when I use a LinkColumn with this DateTimeField, the dates are displayed in a complex format like this: '2017-02-23 07:49:53.067504+00:00' instead of '23.02.2017 07:49'. The links work fine but I can't find a way to get back to the simple format.

The LinkColumn looks like this

My model in models.py:

class mymodel(models.Model):
Date = models.DateTimeField(auto_now_add=True, help_text='(Format: TT.MM.JJJJ)')

...other fields...

class Meta:
    ordering = ["Date"]
    verbose_name = "MyModel"
    verbose_name_plural = "MyModels"

and the table:

class MyModelTable(django_tables2.Table):
Date = django_tables2.LinkColumn(viewname='MyModelView', kwargs={"id": Accessor("id")})
class Meta:
    model = MyModel
    exclude = {'id'}
    attrs = {"class": "paleblue"}

Thanks in advance for any help or ideas.

Nkls155
  • 273
  • 1
  • 4
  • 13

1 Answers1

2

LinkColumn converts the value in the column to string and doesn't care about dates. You can use the text argument to LinkColumn to pass a callable to use render the value in a custom way.

For example:

class MyModelTable(django_tables2.Table):
    Date = django_tables2.LinkColumn(
        viewname='MyModelView', 
        kwargs={"id": Accessor("id")},
        text=lambda record: record.Date.strftime('%x %X')
    )

    class Meta:
        model = MyModel
        exclude = {'id'}

Will render both date and time using format string %x %X, documentation here.

Note that if this field is nullable, you should add a check for that in the callable you pass with text.

Jieter
  • 4,101
  • 1
  • 19
  • 31