简体   繁体   English

如何反转 django 中包含的 url 的“url”

[英]How to reverse 'url' of included urls in django

Suppose my projects urls.py looks something like this:假设我的项目urls.py看起来像这样:

urlpatterns = [
    path("admin/", admin.site.urls),
    path("foo/", include("foo.urls"), name="foo"),
]

Then I have a file foo/urls.py , that has some further urls:然后我有一个文件foo/urls.py ,它有一些进一步的 url:

urlpatterns = [
    path("bar/", views.bar, name="bar"),
    path("baz/", views.baz, name="baz"),
]

What I would like to do我想做什么

Get the 'partial' url that takes you so far as the included 'urls'.获取“部分”url,它将带您到包含的“url”。 For example, I could do reverse("bar") to get foo/bar .例如,我可以做reverse("bar")来获得foo/bar But I can't seem to do reverse('foo') to get just foo`.但我似乎不能做reverse('foo') to get just foo`。 Is there a way of doing this.有没有办法做到这一点。

One (unideal) solution一种(不理想的)解决方案

I could put a dummy view inside foo/urls.py right at the very end with a path of "" , and then reverse this.我可以在foo/urls.py的最后放置一个虚拟视图,路径为"" ,然后将其反转。 However I don't like this solution.但是我不喜欢这个解决方案。 It feels hacky, and would potentially have problems if a user ever hit this URL.感觉很hacky,如果用户点击这个URL,可能会遇到问题。

Your unideal solution is actually exactly how it would be intended in Django.您不理想的解决方案实际上正是 Django 中的预期方式。 That means adding a path in foo.urls : path("", views.index, name="foo") .这意味着在foo.urls中添加一个路径: path("", views.index, name="foo")

I understand that this feels hacky to you, but currently the /foo path refers to no resource on your server, as no path for it has been defined.我知道这对您来说感觉很奇怪,但目前 /foo 路径没有引用您服务器上的资源,因为尚未定义它的路径。 It would make no sense for Django to ever even be able to reverse this path, as it points to nothing. Django 甚至能够扭转这条道路是没有意义的,因为它什么都没有。

If you still want to reverse the path, while Django would return a 404 error, you would actually have to define a simple view returning a 404 response.如果您仍想反转路径,而 Django 将返回 404 错误,您实际上必须定义一个返回 404 响应的简单视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM