[英]Pass a datetime object to url in django
How can I pass a datetime eg datetime.date(2017, 12, 31) object to a url in django?如何将日期时间(例如datetime.date(2017, 12, 31)对象)传递给 django 中的 url?
My template:我的模板:
{% for key, value in my_dictionary.items %}
{{ key.0 }} # it displays Dec. 31, 2017
...
{% endfor %}
Passing it to the url as:将其传递给 url:
href="{% url 'my_url:my_date' selected_day=key.0 %}">
My urls.py:我的 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
.您的 url 模式中的组
selected_day
只能包含单词字符\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.如果您对日期字符串使用 iso8601 日期格式,则可以使用此 url 模式。
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).简单地在日期对象上使用
str(date)
应该默认使用 iso 格式 (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.
但是 django QuerySets 将接受日期字符串作为参数,因此可能不需要该步骤。
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
Django 还包含一个实用函数,可用于解析日期字符串:
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
示例:
2019-07-18T17:12:32.909Z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.