Saturday, February 13, 2016

Mismatch between the "date" template filter 'W' and strptime '%W'

Hi folks,

We just tried to use the built-in WeekArchiveView, and we hit a snag
when trying to reverse URLs pointing to it from within templates using
something like::

{% url "my-weekly-archive" next_week|date:"Y" next_week|date:"W" %}

The docs for WeekArchiveView [1] state::

The '%W' format uses the ISO week format and its week begins on a
Monday. The '%W' format is the same in both the strftime() and the
date.

The problem is, week numbers generated by the "date" template filter
do not always match week numbers parsed by strptime.

For instance, take the date 2015-11-16. The "date" template filter
uses formatters defined in django.utils.dateformat, and for this date,
it returns::

>>> from datetime import date
>>> from django.utils import dateformat
>>> dateformat.format(date(2015, 11, 16), 'W')
'47'

However, when you try to parse that back into a datetime using the
same algorithm as the one used in WeekArchiveView, you get a different
date::

>>> from datetime import datetime
>>> datetime.strptime('2015 1 47', '%Y %w %W')
datetime.datetime(2015, 11, 23, 0, 0)

I found a ticket dealing with exactly this problem [2], but it's been
closed seven years ago as wontfix, because of backwards compatibility
(which I totally understand). However, what I don't understand is the
suggestion to use the url template tag – that's what we've been doing
all along, I thought reverse() and the url template tag expect the
same number of arguments as what the named urlpattern captures, and
just coerce them into strings in the simplest way possible. Am I
missing some magic feature in the URL reverser that would be able to
understand that the two numbers captured in a urlpattern are a year
and week number, and translate a date object into the correct numbers?

Or is there anything else that I am missing? From what I understand,
all date-based archive views only pass date objects into the template
context (as {next,previous}_{week,year,...}), not the numbers expected
in their URLs.

In any case, that sentence in the docs I quoted above is evidently
incorrect, so I created a ticket for it [3].

Cheers,

Michal


[1]: https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-date-based/#weekarchiveview
[2]: https://code.djangoproject.com/ticket/7380
[3]: https://code.djangoproject.com/ticket/26217

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20160213214005.GN2245%40koniiiik.org.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment