开发者

URL to date-based generic view in django template?

开发者 https://www.devze.com 2022-12-18 06:01 出处:网络
Is there an easy way to get the URL to a Django date-based generic view (specifically object_detail) from a template?

Is there an easy way to get the URL to a Django date-based generic view (specifically object_detail) from a template?

Given a URL conf like this

url(r'^posts/(?P<year>\d\d\d\d)/(?P<month>\d\d)/(?P<day>\d\d)/(?P<slug>[\w-]+)$', 'date_based.object_detail', detail_info, name='blog-post-detail')

My understanding is that I would need to do something like this

{% url blog_post_detail year=post.date.year.str,month=post.date.month,day=post.date.day,slug=post.slug %}

Except that

  1. The year, month and day need to be formatted as strings
  2. There has to be an easier way

If anyo开发者_高级运维ne has input on either of these it would be much appreciated

Thanks


The easier and better way is to define this reverse in the BlogPost model within get_absolute_url and in the template use {{blogpost.get_absolute_url}}

Update:

Assuming you are storing the date in the models.DateField or models.DateTimeField, the string conversion can be achieved by date.strftime("%Y/%b/%d").lower()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号