将日期时间对象传递给Django中的url [英] Pass a datetime object to url in django

查看:50
本文介绍了将日期时间对象传递给Django中的url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何传递日期时间,例如 datetime.date(2017,12,31)是否指向Django中的网址?

How can I pass a datetime e.g. datetime.date(2017, 12, 31) object to a url in django?

我的模板:

{% 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 %}">

我的urls.py:

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

错误:

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+)/$']

推荐答案

URL模式中的 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')

如果您对日期字符串使用iso8601日期格式,则可以使用此网址格式.

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')

在日期对象上仅使用 str(date)即可,默认情况下应使用iso格式(YYYY-MM-DD).您可以在视图函数中将日期字符串解析为日期对象.但是django QuerySet将接受日期字符串作为参数,因此可能无需执行此步骤.

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还包括一个实用程序函数,可用于解析日期字符串: django.utils.dateparse.parse_date

Django also includes a utility function you can use to parse date strings: django.utils.dateparse.parse_date

这篇关于将日期时间对象传递给Django中的url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆