How can I pass a datetime eg datetime.date(2017, 12, 31) object to a url in django?
My template:
{% for key, value in my_dictionary.items %}
{{ key.0 }} # it displays Dec. 31, 2017
...
{% endfor %}
Passing 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+)/$']
The group selected_day
in your url pattern can only contain word characters \w
. That includes digits, but not spaces or dashes.
url(r'^my-date/(?P<selected_day>\w+)/$', name='my_date')
If you use iso8601 date format for your date string, you can use this url pattern.
url(r'^my-date/(?P<selected_day>\d{4}-\d{2}-\d{2})/$', name='my_date')
Simply using str(date)
on a date object should use iso format by default (YYYY-MM-DD). You can parse the date string to a date object in you view function. But django QuerySets will accept date strings as arguments, so that step might 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 you can use to parse date strings: django.utils.dateparse.parse_date
You cant, convert datetime object to string and pass that.
t = datetime.date(2017, 12, 31)
t.strftime('%m/%d/%Y')
This will yield
'02/23/2012'
pass that to your url.
If you are using timezone aware dates (which you should), would be this:
r'^(?P<date_start>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)/'
Example: 2019-07-18T17:12:32.909Z
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.