url patterns to acccess views of app in Django
问题
The difference between the following url patterns in main project of Django?
from testinclude import views as subViews
sub=[path("sub/",subViews.useincludetest)]
urlpatterns = [
path("root1/",include('testinclude.urls')),
path("root2/",subViews.useincludetest),
path("root3/",include(sub))
]
I have created a testinclude app, and the urls.py and views.py of test include as below:
1.urls.py of testinclude app
from . import views as testincludeview
urlpatterns =[
path("testinclude/",testincludeview.useincludetest)
]
2.views.py of testinclue app
def useincludetest(request):
return HttpResponse("这是应用testinclude下的useincludetest函数响应")
回答
In the main project's urlpatterns
, the first pattern, path("root1/", include('testinclude.urls'))
, includes all the URL patterns defined in the urls.py
file of the testinclude
app. This means that any URL that starts with root1/
will be handled by the URL patterns defined in the urls.py
file of the testinclude
app.
The second pattern, path("root2/", subViews.useincludetest)
, maps the URL root2/
to the useincludetest
view function defined in the views.py
file of the testinclude
app. This pattern does not use the include()
function, and simply maps the URL to the specified view function.
The third pattern, path("root3/", include(sub))
, includes a list of URL patterns defined in the sub
variable. In this case, the sub
variable is defined as [path("sub/", subViews.useincludetest)]
, which means that any URL that starts with root3/sub/
will be handled by the useincludetest
view function defined in the views.py
file of the testinclude
app.
And just to clarify, the three URL patterns you listed at the end should work with the following views respectively:
- http://127.0.0.1:8000/root1/testinclude/ :
testincludeview.useincludetest
- http://127.0.0.1:8000/root2/ :
subViews.useincludetest
- http://127.0.0.1:8000/root3/sub/ :
testincludeview.useincludetest
(since thesub
list is just a list of URL patterns that are passed to theinclude()
function, and theinclude()
function simply includes all of those patterns under the specified URL prefix, which in this case isroot3/sub/
)
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2022-03-26 思想道德与法治
2022-03-26 word菜单识别 文本编辑
2019-03-26 Grid布局教程
2019-03-26 List of 3rd Party .NET UI & Reporting Components
2018-03-26 git fetch批处理,遍历一个文件夹下的所有子目录,执行git fetch --all
2016-03-26 Google Deepmind AI tries it hand at creating Hearthstone and Magic: The Gathering cards