前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django小技巧01: redirect

Django小技巧01: redirect

作者头像
用户1416054
发布2018-12-04 09:43:27
1.2K0
发布2018-12-04 09:43:27
举报
文章被收录于专栏:JackeyGao的博客JackeyGao的博客

#redirect

翻译整理自: simpleisbetterthancomplex.com

Python

代码语言:javascript
复制
from django.shortcuts import redirect

redirect函数会返回一个HttpResponseRedirect类,比起HttpResponseRedirect类我更喜欢使用更简洁的redirect. 它会使我的代码保持一致。

推荐使用 redirect 的理由是, 您可以指定不同类型的参数(model, url, endpoint),指定 endpoint 的时候还可以直接指定URL, 不用再用django.urlresolvers.reverse来解析一遍了, 简洁了作用域环境.

下面我们来看看实例:

  • 一个模型实例, 这将自动调用模型的get_absolute_url()方法;

Python

代码语言:javascript
复制
from django.shortcuts import redirect
from simple_blog.models import Post

def post_view(request, post_id):
    post = Post.objects.get(pk=post_id)
    return redirect(post)
    # equivalent to: return HttpResponseRedirect(post.get_absolute_url())
  • 反解析endpoint URL 名称(接受视图 endpoint 参数)

Python

代码语言:javascript
复制
from django.shortcuts import redirect
from simple_blog.models import Post

def post_view(request, post_id):
    return redirect('post_details', id=post_id)
    # equivalent to: return HttpResponseRedirect(reverse('post_details', args=(post_id, )))
  • 原始URL (aboluste 或者 relative)

Python

代码语言:javascript
复制
from django.shortcuts import redirect

def relative_url_view(request):
    return redirect('/posts/archive/')
    # equivalent to: return HttpResponseRedirect('/posts/archive/')

def absolute_url_view(request):
    return redirect('https://simpleblog.com/posts/archive/')
    # equivalent to: return HttpResponseRedirect('https://simpleblog.com/posts/archive/')

阅读更多关于redirect的文档. Django Documentation

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档