Django Include() in urls.py with two apps

戏子无情 提交于 2021-02-08 11:37:49

问题


I believe this is a simple question but I am having a hard time figuring out why this is not working.

I have a django project and I've added a second app (sales). Prior to the second app, my urls.py simply routed everything to the first app (chart) with the following:

urlpatterns = [

    path('admin/', admin.site.urls),
    path('', include('chart.urls')),
]

and it worked fine.

I have read the docs over and over a looked at many tutorials, so my impression is that I can simply amend the urls.py to include:

urlpatterns = [

    path('admin/', admin.site.urls),
    path('sales/', include('sales.urls')),
    path('', include('chart.urls')),
]

and it should first look for a url with sales/ and if it finds that then it should route it to sales.urls, and if it doesn't find that then move on and route it to chart.urls. However, when I load this and type in 127.0.0.1:8000/sales, it returns the following error:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/sales/
Raised by:  chart.views.index

which tells me that it is not routing my sales/ url to sales.urls but to chart.urls. When I change path('', include('chart.urls')), to path('', include('sales.urls')), it does route it to sales.urls so I know that my sales.urls file is set up correctly.

I know this is probably an easy question but I cannot figure it out with anything I've read. Any help is appreciated.

chart.urls:

from django.urls import path, re_path
from . import views

urlpatterns = [
    path('dashboard/', views.chart, name='dashboard'),
    path('', views.index, name='index', kwargs={'pagename': ''}),
    path('<str:pagename>/', views.index, name='index'),
]

sales.urls:

from django.urls import path
from . import views

urlpatterns = [
    path('sales/', views.sales, name='Sales Dashboard'),
]

回答1:


I think the correct url for the sales page in your case would be http://127.0.0.1:8000/sales/sales/.

This is because sales/ is then looking in the included sales.urls and not finding any urls at the root / (the only url included there is at sales/ (within sales/) so will be sales/sales/

Reply to an OLD question but may be useful for others...




回答2:


from django.urls import path, include

dont for get to import include




回答3:


Do this:

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('chart.urls')),
    url(r'^sales/', include('sales.urls')),
]

you are not doing it properly since you are not telling your app where go once it is loaded .this r'^' to go directly to chart.url url(r'^', include('chart.urls')),



来源:https://stackoverflow.com/questions/51724903/django-include-in-urls-py-with-two-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!