Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
301 Django项目重定向路由器_Django_Django Urls - Fatal编程技术网

301 Django项目重定向路由器

301 Django项目重定向路由器,django,django-urls,Django,Django Urls,我有一个网站建设工具在Django创建,我想添加简单的用户定义301重定向到它 Webflow有一个非常容易理解的301重定向工具。添加一条路径(不仅仅是一个slug),然后定义该路径应该引导用户的位置 我想为我正在从事的Django项目做同样的事情。我目前允许用户设置一个slug重定向/,他们可以设置为转到任何URL。但我希望他们能够添加,例如,一篇旧博客文章的路径'/2018/04/12/我最喜欢的东西/' 在Django中,安全接受用户想要的任何路径的最佳URL配置是什么?您可以使用将路

我有一个网站建设工具在Django创建,我想添加简单的用户定义301重定向到它

Webflow有一个非常容易理解的301重定向工具。添加一条路径(不仅仅是一个slug),然后定义该路径应该引导用户的位置

我想为我正在从事的Django项目做同样的事情。我目前允许用户设置一个slug重定向
/
,他们可以设置为转到任何URL。但我希望他们能够添加,例如,一篇旧博客文章的路径
'/2018/04/12/我最喜欢的东西/'

在Django中,安全接受用户想要的任何路径的最佳URL配置是什么?

您可以使用将路径参数转换为适当类型的,其中还包括URL转换器

示例如下所示:

path('api/<path:encoded_url>/', YourView.as_view()),

添加一个
重路由中间件
,该中间件首先检查请求是否可以由
url.py中的现有URL提供服务。如果无法提供服务,请检查请求的路径是否来自old->newURL映射,如果找到匹配项,请将其重定向到新URL

测试它的代码示例

    try:
        resolve(request.path_info)
    except Resolver404:
        # Check if the URL exists in your database/constants 
        # where you might have stored the old -> new URL mapping.
        if request.path is valid:
            new_url = # Retrieve the new URL
            return redirect(new_url)

    response = self.get_response(request)
    return response

您可能需要将该链接替换为以下链接:@SMoenig更新了该链接,谢谢提醒!我已经发布了答案,有帮助吗?如果没有,你能说出遗漏了什么吗?我很乐意帮忙;谢谢你接受这个答案,我很高兴它有帮助!别忘了奖励赏金,这样它就不会消失。
    try:
        resolve(request.path_info)
    except Resolver404:
        # Check if the URL exists in your database/constants 
        # where you might have stored the old -> new URL mapping.
        if request.path is valid:
            new_url = # Retrieve the new URL
            return redirect(new_url)

    response = self.get_response(request)
    return response