Python – Pass a datetime object to a URL in django

Pass a datetime object to a URL in django… here is a solution to the problem.

Pass a datetime object to a URL in django

How do I pass a datetime, such as datetime.date(2017, 12, 31) object to a URL in Django?

My templates:

{% for key, value in my_dictionary.items %}
    {{ key.0 }}  # it displays Dec. 31, 2017
    ...
{% endfor %} 

Pass it to the url as:

href="{% url 'my_url:my_date' selected_day=key.0 %}">

My urls.py:

url(r'^my-date/(? P<selected_day>\w+)/$', name='my_date')

Error:

Exception Type: NoReverseMatch
Exception Value: Reverse for 'my_date' with keyword arguments 
'{'selected_day': datetime.date(2017, 12, 31),}'not found. 1 pattern(s) tried: ['my-url/my-date/(? P<selected_day>\\w+)/$']

Solution

Group selected_day in your URL pattern can only contain the word character \w. This includes numbers, but not spaces or dashes.

url(r'^my-date/(? P<selected_day>\w+)/$', name='my_date')

You can use this URL pattern if your date string uses the ISO8601 date format.

url(r'^my-date/(? P<selected_day>\d{4}-\d{2}-\d{2})/$', name='my_date')

Simply using str(date) on date objects should default to ISO format (YYYY-MM-DD). You can parse a date string into a date object in the View function. However, django QuerySets will accept a date string as a parameter, so this step may not be needed.

def my_date_view(request, selected_day):
    # this works with either a date object or a iso formatted string.
    queryset = MyModel.objects(published_on=selected_day) 

# or use strptime to get a date object.
    date = datetime.datetime.strptime(selected_day, '%Y-%M-%d').date()

Django also includes a utility function that can be used to parse date strings: > django.utils.dateparse.parse_date


Related Problems and Solutions