问题

The difference between the following url patterns in main project of Django?from testinclude import views as subViewssub=[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 appfrom . import views as testincludeviewurlpatterns =[    path("testinclude/",testincludeview.useincludetest)]

2.views.py of testinclue appdef 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 the sub list is just a list of URL patterns that are passed to the include() function, and the include() function simply includes all of those patterns under the specified URL prefix, which in this case is root3/sub/)

 

精彩文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。