【问题标题】:Django redirect URL to latest created blog postDjango 将 URL 重定向到最新创建的博客文章
【发布时间】:2011-07-23 08:30:15
【问题描述】:

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

Blog.Post 详细信息是通过 blog.views.post_detail(request, slug) 方法提供的,并且博客文章将以 URL 结尾:

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

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

我对 urls.py 非常陌生,不知道如何执行此操作。我意识到这将是相当初级的。

【问题讨论】:

    标签: django django-templates django-views


    【解决方案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]))
    

    另一种选择,有些人不喜欢反向,因为它失败得很厉害。

    你可以在你的博客文章模型上定义一个get_absolute_url方法来返回绝对url,那么你的重定向就像http.HttpResponseRedirect(Blog.objects.latest('id').get_absolute_url()一样简单)

    【讨论】:

    • 我收到了:NoReverseMatch at /blog/ Reverse for 'post_detail' with arguments '()' and keyword arguments '{}' not found. 看来我正朝着正确的方向前进 - 对此有什么想法吗?
    • 没关系,找到它,必须在反向方法中移动 args,例如 return http.HttpResponseRedirect(reverse('blog_detail', args=[blog.slug]))。谢谢,效果很好!
    • 糟糕,这是一个错字!对不起,如果这让你困惑了一段时间:D
    猜你喜欢
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2015-07-26
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多