gpt4 book ai didi

python - Django 使用 include() 作为 path() 参数

转载 作者:行者123 更新时间:2023-12-04 10:11:02 26 4
gpt4 key购买 nike

我正在学习 Django。

tutorial它说:

The path() function is passed four arguments, two required: route and view, and two optional: kwargs, and name. At this point, it’s worth reviewing what these arguments are for.

path() argument: view

When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. We’ll give an example of this in a bit.



在我看来, view是一个接受 HttpRequest 的函数作为参数并返回 HttpResponse .

但在 mysite/urls.py path()像这样使用 path("polls/", include("polls.urls")) ,
inclue方法返回一个元组 (urlconf_module, app_name, namespace) ,不是函数。

为什么可以 include()在这里使用?

如果有人可以提供帮助,我将不胜感激。

最佳答案

documentation

The view argument is a view function or the result of as_view() for class-based views. It can also be an django.urls.include().



如果你查看源代码,
def _path(route, view, kwargs=None, name=None, Pattern=None):
if isinstance(view, (list, tuple)):
# For include(...) processing.
pattern = Pattern(route, is_endpoint=False)
urlconf_module, app_name, namespace = view
return URLResolver(
pattern,
urlconf_module,
kwargs,
app_name=app_name,
namespace=namespace,
)
elif callable(view):
pattern = Pattern(route, name=name, is_endpoint=True)
return URLPattern(pattern, view, kwargs, name)
else:
raise TypeError('view must be a callable or a list/tuple in the case of include().')

你会看到它只是检查参数类型并根据它是元组还是可调用来做不同的事情。

关于python - Django 使用 include() 作为 path() 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61335284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com