|
4 | 4 | from django.contrib.contenttypes.fields import GenericForeignKey |
5 | 5 | from django.contrib.contenttypes.models import ContentType |
6 | 6 | from django.core.exceptions import FieldDoesNotExist |
| 7 | +from django.db.models import DateField, DateTimeField |
7 | 8 | from django.db.models.fields.related import RelatedField |
8 | 9 | from django.urls import reverse |
| 10 | +from django.utils.formats import date_format |
9 | 11 | from django.utils.safestring import mark_safe |
10 | 12 | from django_tables2 import RequestConfig |
| 13 | +from django_tables2.columns import library |
11 | 14 | from django_tables2.data import TableQuerysetData |
12 | 15 | from django_tables2.utils import Accessor |
13 | 16 |
|
@@ -205,6 +208,42 @@ def value(self, **kwargs): |
205 | 208 | return ret |
206 | 209 |
|
207 | 210 |
|
| 211 | +@library.register |
| 212 | +class DateColumn(tables.DateColumn): |
| 213 | + """ |
| 214 | + Overrides the default implementation of DateColumn to better handle null values, returning a default value for |
| 215 | + tables and null when exporting data. It is registered in the tables library to use this class instead of the |
| 216 | + default, making this behavior consistent in all fields of type DateField. |
| 217 | + """ |
| 218 | + |
| 219 | + def value(self, value): |
| 220 | + return value |
| 221 | + |
| 222 | + @classmethod |
| 223 | + def from_field(cls, field, **kwargs): |
| 224 | + if isinstance(field, DateField): |
| 225 | + return cls(**kwargs) |
| 226 | + |
| 227 | + |
| 228 | +@library.register |
| 229 | +class DateTimeColumn(tables.DateTimeColumn): |
| 230 | + """ |
| 231 | + Overrides the default implementation of DateTimeColumn to better handle null values, returning a default value for |
| 232 | + tables and null when exporting data. It is registered in the tables library to use this class instead of the |
| 233 | + default, making this behavior consistent in all fields of type DateTimeField. |
| 234 | + """ |
| 235 | + |
| 236 | + def value(self, value): |
| 237 | + if value: |
| 238 | + return date_format(value, format="SHORT_DATETIME_FORMAT") |
| 239 | + return None |
| 240 | + |
| 241 | + @classmethod |
| 242 | + def from_field(cls, field, **kwargs): |
| 243 | + if isinstance(field, DateTimeField): |
| 244 | + return cls(**kwargs) |
| 245 | + |
| 246 | + |
208 | 247 | class ButtonsColumn(tables.TemplateColumn): |
209 | 248 | """ |
210 | 249 | Render edit, delete, and changelog buttons for an object. |
|
0 commit comments