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:

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用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
点击右上角即可分享
微信分享提示