python - View 功能之外的 Django HTTP 重定向

标签 python django django-views python-2.6

有没有办法在 View 函数之外重定向到 Django 中的另一个页面。

我需要能够在我的应用程序中的任何地方重定向,而不仅仅是在我将 HTTP 响应返回给客户端时。

我试过重定向快捷方式:

from django.shortcuts import redirect
redirect("/some/url")

还有

redirect("http://someserver.com/some/url")

但这并没有明显的作用。

我需要 PHP 中的 header("Location:/some/url"); 之类的东西,它可以在脚本中的任何地方使用。

谢谢

最佳答案

您可以滥用/利用中间件的 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)

然后你可以这样做:

from middleware import redirect
redirect('/some/url/')

另外不要忘记将 RedirectMiddleware 添加到您的 MIDDLEWARE_CLASSES 设置中。

关于python - View 功能之外的 Django HTTP 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13677159/

相关文章:

python - 如何处理CreateView中的对象引用

python - 操作多维集 : marginalization, 扩展名、成员资格

python - 当内存有问题时如何读取大型 csv 或数据库并连接列?

python - django/whitenoise 存储后端导致错误

python - 这是使用 API 在 Python 中为 Braintree 创建订阅的正确方法吗

django - 无法为 API 设置 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' 导入 'DEFAULT_AUTHENTICATION_CLASSES'

python - 我如何使用 Tensorflow 的调试器来解决 "Getting Started"示例中的分歧?

python - 如何找到节点的马尔可夫毯?

django - Pytest 装置相互干扰

python - 无法导入名称 import_by_path