`TypeError` when using a `DateColumn`
jhonatan-lopes opened this issue · comments
Issue Summary
When using a DateColumn
on a Django DateField
, the template rendering gives:
TypeError: The format for date objects may not contain time-related format specifiers (found 'P').
Steps to Reproduce
- Start a new project with
wagtail start myproject
- Create a model with a
DateField
- Add a
SnippetViewSet
with aDateColumn
for theDateField
- Go to the CMS admin and into the snippets menu
- See Error
# models.py
from django.db import models
class MyModel(models.Model):
my_date_field = DateField(auto_add_now=True)
# wagtail_hooks.py
from wagtail.admin.ui.tables import DateColumn
from wagtail.snippets.views.snippets import SnippetViewSet
from .models import MyModel
class MyModelSnippetViewSet(SnippetViewSet):
model = MyModel
list_display = (
DateColumn("my_date_field"),
)
Any other relevant information. For example, why do you consider this a bug and what did you expect to happen instead?
- I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: (yes / no)
Technical details
- Python version: 3.11
- Django version: 4.2
- Wagtail version: 5.2.2
- Browser version: irrelevant, it will happen in all browsers.
Working on this
Anyone can contribute to this. View our contributing guidelines, add a comment to the issue once you’re ready to start.
This is caused by the human_readable_date
template tag used in the DateColumn
. The tag wrongly assumes a DATETIME_FORMAT
for rendering the date
on the tooltip. This works for datetime values but not for dates:
<button type="button" class="w-human-readable-date" data-controller="w-tooltip" data-w-tooltip-content-value="{{ date|date:"DATETIME_FORMAT" }}" data-w-tooltip-placement-value="{{ placement }}">
...
</button>
If not specified, the DATETIME_FORMAT
here defaults to the Django default of 'N j, Y, P'
. The P
specifies the time in the datetime object. Since the date object doesn't have a time, it triggers the exception. The correct format here should be DATE_FORMAT
(default 'N j, Y'
in Django).
To solve this, the human_readable_date
component should be able to detect if the input is a date or datetime object and adjust the format accordingly.
I'm working on this