我目前正在使用Django 1.11.2和django-tables2进行一个项目。我用一张桌子来显示我的模型。该模型有一个DateTimeField,它在普通列中正确显示,但是当我使用带有此DateTimeField的LinkColumn时,日期以复杂的格式显示,如下所示:'2017-02-23 07:49:53.067504 + 00:00 '而不是'23 .02.2017 07:49'。 链接工作正常,但我找不到回归简单格式的方法。
我的模型在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"
和表格:
class MyModelTable(django_tables2.Table):
Date = django_tables2.LinkColumn(viewname='MyModelView', kwargs={"id": Accessor("id")})
class Meta:
model = MyModel
exclude = {'id'}
attrs = {"class": "paleblue"}
提前感谢任何帮助或想法。
答案 0 :(得分: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
.