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

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

问题描述

我想在我的 urls.py 中进行重定向,以便在人们访问博客应用程序索引域时自动加载我博客应用程序中最新的 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 方法来返回绝对 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天全站免登陆