问题
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/
)