问题
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