Use ISO 8601 format when displaying dates & times in a table

This commit is contained in:
Jeremy Stretch 2024-04-16 16:59:12 -04:00
parent e104fab50b
commit cdbb700c8f
2 changed files with 15 additions and 16 deletions

View File

@ -30,10 +30,10 @@ class UserTokenTable(NetBoxTable):
write_enabled = columns.BooleanColumn(
verbose_name=_('Write Enabled')
)
created = columns.DateColumn(
created = columns.DateTimeColumn(
verbose_name=_('Created'),
)
expires = columns.DateColumn(
expires = columns.DateTimeColumn(
verbose_name=_('Expires'),
)
last_used = columns.DateTimeColumn(

View File

@ -10,7 +10,6 @@ from django.db.models import DateField, DateTimeField
from django.template import Context, Template
from django.urls import reverse
from django.utils.dateparse import parse_date
from django.utils.formats import date_format
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
@ -52,18 +51,17 @@ __all__ = (
#
@library.register
class DateColumn(tables.DateColumn):
class DateColumn(tables.Column):
"""
Overrides the default implementation of DateColumn to better handle null values, returning a default value for
tables and null when exporting data. It is registered in the tables library to use this class instead of the
default, making this behavior consistent in all fields of type DateField.
Render a datetime.date in ISO 8601 format.
"""
def render(self, value):
if value:
return date_format(value, format="SHORT_DATE_FORMAT")
return value.isoformat()
def value(self, value):
return value
if value:
return value.isoformat()
@classmethod
def from_field(cls, field, **kwargs):
@ -72,16 +70,17 @@ class DateColumn(tables.DateColumn):
@library.register
class DateTimeColumn(tables.DateTimeColumn):
class DateTimeColumn(tables.Column):
"""
Overrides the default implementation of DateTimeColumn to better handle null values, returning a default value for
tables and null when exporting data. It is registered in the tables library to use this class instead of the
default, making this behavior consistent in all fields of type DateTimeField.
Render a datetime.datetime in ISO 8601 format.
"""
def render(self, value):
if value:
return f"{value.date().isoformat()} {value.time().isoformat(timespec='seconds')}"
def value(self, value):
if value:
return date_format(value, format="SHORT_DATETIME_FORMAT")
return None
return value.isoformat(timespec='seconds')
@classmethod
def from_field(cls, field, **kwargs):
@ -498,7 +497,7 @@ class CustomFieldColumn(tables.Column):
if self.customfield.type == CustomFieldTypeChoices.TYPE_LONGTEXT and value:
return render_markdown(value)
if self.customfield.type == CustomFieldTypeChoices.TYPE_DATE and value:
return date_format(parse_date(value), format="SHORT_DATE_FORMAT")
return parse_date(value).isoformat()
if value is not None:
obj = self.customfield.deserialize(value)
return mark_safe(self._linkify_item(obj))