Mic*_*tes 6 python django python-2.6 django-views
有没有办法在视图函数之外重定向到Django中的另一个页面.
我需要能够在我的应用程序中的任何位置重定向,而不仅仅是当我将HTTP响应返回给客户端时.
我尝试过重定向快捷方式:
from django.shortcuts import redirect
redirect("/some/url")
Run Code Online (Sandbox Code Playgroud)
并且
redirect("http://someserver.com/some/url")
Run Code Online (Sandbox Code Playgroud)
但这没有明显的行动.
我需要像header("Location: /some/url");PHP这样的东西,可以在脚本中的任何地方使用.
谢谢
您可能滥用process_exception中间件:
# middleware.py
from django import shortcuts
class Redirect(Exception):
def __init__(self, url):
self.url = url
def redirect(url):
raise Redirect(url):
class RedirectMiddleware:
def process_exception(self, request, exception):
if isinstance(exception, Redirect):
return shortcuts.redirect(exception.url)
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
from middleware import redirect
redirect('/some/url/')
Run Code Online (Sandbox Code Playgroud)