如何覆盖具有命名空间url模式的Django视图? [英] How to override Django view that has a namespaced url pattern?

查看:56
本文介绍了如何覆盖具有命名空间url模式的Django视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我最喜欢的名为 foo 的外部应用程序,但是我需要扩展一个名为 Bar 的特定视图的功能.通常,我只是将扩展视图放在 include('foo.urls')之前的 urls.py 中,并命名相同,以便解析程序首先点击它:

I'm using external application called foo which I mostly like, but I need to extend functionality of one specific view called Bar. Normally, I'd just put my extended view in urls.py before include('foo.urls') and name it the same, so that resolver hits it first:

urlpatterns = [
    ...
    url(r'^foo/path_to_bar$', CustomBar.as_view(), name='bar'),
    url(r'^foo/$', include('foo.urls')),
    ...
]

问题是, foo 到处都使用命名空间的url,因此实际上,该视图是由 foo:bar include()引用的.上面的code>声明实际上应该是:

The problem is, foo uses namespaced urls everywhere, so the view in question is actually referred to by foo:bar and the include() declaration above should actually be:

include('foo.urls', namespace='foo', app_name='foo')

这显然对可重用的应用程序非常有用,但是我很难找到在我的项目中覆盖此视图的方法.有没有办法在不重写对 reverse()的所有调用以及在 foo 中使用 {%url%} 的情况?从本质上讲,这将构成应用程序的分支,并且首先失去了重用视图的目的.

This is apparently great for resuable apps, but I have hard time finding the way to override this view in my project. Are there any means to do so, without rewriting all calls to reverse() and uses of {% url %} in foo? That would esentially amount to forking the app and defeat the purpose of reusing a view in the first place.

推荐答案

我不确定我是否理解此问题. {%url'foo:foo'%} 将与应用程序中的url模式匹配,并返回/foo/path_to_bar/.然后,该URL将与您的自定义URL模式匹配.您的自定义视图的网址格式的名称无关紧要.

I'm not sure I understand the problem. {% url 'foo:foo' %} will match the url pattern in the app, and return /foo/path_to_bar/. That URL will then be matched by your custom URL pattern. The name of the URL pattern of your custom view shouldn't matter.

如果原始应用使用与 path_to_bar 不同的URL,则该方法将无效.在这种情况下,您仍然不必将所有调用都更改为 reverse -只需创建自己的 my_foo_urls.py ,复制 foo/urls的内容即可.py ,并包含它.

That won't work if the original app uses a different URL than path_to_bar. In this case you still don't have to change all the calls to reverse - just create your own my_foo_urls.py, duplicate the contents of foo/urls.py, and include that instead.

这篇关于如何覆盖具有命名空间url模式的Django视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆