Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.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
Python 有没有可能给Django';那倒过来?_Python_Django_Monkeypatching - Fatal编程技术网

Python 有没有可能给Django';那倒过来?

Python 有没有可能给Django';那倒过来?,python,django,monkeypatching,Python,Django,Monkeypatching,我们的一些URL包括#。它们用于反向查找,使用reverse和{%url模板标记(内部使用reverse)。Django 1.8以前不使用它,现在1.11将其编码为%23 有没有可能在某处放置一个猴子补丁包装器,并让它在任何地方都能使用?这是我的包装器: def patch_reverse(func): def inner(*args, **kwargs): print "inner reverse" url = func(*args, **kwargs)

我们的一些URL包括
#
。它们用于反向查找,使用
reverse
{%url
模板标记(内部使用
reverse
)。Django 1.8以前不使用它,现在1.11将其编码为
%23

有没有可能在某处放置一个猴子补丁包装器,并让它在任何地方都能使用?这是我的包装器:

def patch_reverse(func):
    def inner(*args, **kwargs):
        print "inner reverse"
        url = func(*args, **kwargs)
        return url.replace("%23", "#")

    return inner


from django.urls import base
base.reverse = patch_reverse(base.reverse)
print
语句非常简单,因此我可以查看它是否正在实际运行


我试着把它放在设置中,第一个安装的应用程序的
\uuuu init\uuuuu
,以及第一个安装的应用程序的
URL
。什么都不起作用。

当你修补
reverse
时,原来的函数可能已经导入到
django.url
(你通常从那里导入它)和
django.template.defaulttags
(其中
{%url%}
标记使用它。请尝试在这些模块中修补它:

import django.urls
django.urls.reverse = patch_reverse(django.urls.reverse)

import django.template.defaulttags
django.template.defaulttags = patch_reverse(django.template.defaulttags)

这是有效的。在
设置.py
或等效设置模块中:

from django import urls
from django.core import urlresolvers

_django_reverse = urlresolvers.reverse


def _reverse(*args, **kwargs):
    result = _django_reverse(*args, **kwargs)
    # Do whatever you want to do to reverse here
    return result.replace("%23", "#")


urlresolvers.reverse = _reverse
urls.reverse = _reverse

它甚至在
/manage.py shell
中都不起作用。我可以修补原始模块的动态源代码重新加载吗?
django.url.reverse
中的修补
manage.py shell
在我测试它时对我很有效。