Django将URL重定向到最新创建的博文 [英] Django redirect URL to latest created blog post

查看:155
本文介绍了Django将URL重定向到最新创建的博文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的urls.py中重定向,以便当人们访问Blog应用程序索引域时,我的博客应用程序中的最新的Post条目将自动加载。

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.

一个Blog.Post的详细信息是通过blog.views.post_detail(request,slug)方法提供的,一个博客文章最后会出现以下URL:

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/

当某人加载www.example.com/blog域时,我希望他们自动重定向到最新的博客文章。

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

我很新urls.py并且无法解决如何做到这一点。我意识到这将是相当基本的。

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

推荐答案

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.

您可以在返回绝对网址的博客模型上定义一个 get_absolute_url 方法,然后重定向为简单的 http.HttpResponseRedirect(Blog.objects.latest('id')。get_absolute_url()

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

这篇关于Django将URL重定向到最新创建的博文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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