Django redirect URL to latest created blog post

只谈情不闲聊 提交于 2019-12-12 06:38:07

问题


I want to have a redirect in my urls.py so that the latest Post entry in my Blog application is automatically loaded when people visit the Blog application index domain.

A Blog.Post detail is supplied via the blog.views.post_detail(request, slug) method and a blog post will end up with the URL:

www.example.com/blog/this-is-the-slug/

When someone loads the www.example.com/blog domain I want them to be automagically redirected to the latest blog post individual entry.

I'm very new to the urls.py and can't work out how to do this. I realise it would be fairly rudimentary.


回答1:


url(r'^blog/$', 'blog.redirector'),
url(r'^blog/(?P<slug>[-\w]+)/$', 'blog.blog_post', name="blog_detail"),


def redirector(request):
     blog = Blog.objects.latest('id')
     return http.HttpResponseRedirect(reverse('blog_detail', args=[blog.slug]))

Alternative option, some people dislike reverse because it fails loudly.

You can define a get_absolute_url method on your blog post model that returns the absolute url, then your redirect is as simple as http.HttpResponseRedirect(Blog.objects.latest('id').get_absolute_url())



来源:https://stackoverflow.com/questions/5440276/django-redirect-url-to-latest-created-blog-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!