django 2.0 - including urls file from an app to th

2019-07-28 07:41发布

I'm interested in have for each app their own urls.py file and then, include them in the root urls.py file using the include django function like this include('myapp.urls').

Everything here follows the django tutorial: enter link description here

So, in root urls.py it is like this:

from django.url import include, path
urlpatterns = [ path('folio/', include('folio.urls')) ]

and now in the folio urls.py it is like the following:

from django.urls import path
from . import views
urlpatterns = [ path('', views.home, name='home') ]

After some tryings all I get is page not found.

enter image description here

What am I missing?

There's a variation to this to work, in this case I just need to import the app to the root urls.py as following:

from django.url import path
from folio import views
urlspatterns = [ path('', views.home, name='home') ]

1条回答
地球回转人心会变
2楼-- · 2019-07-28 08:06

The page error is very clear. No urls pattern is found in any of your views given your root url '/' or www.example.com/. Since your urls only include admin/ and folio/. No '/' was registered.

But according to your workaround yes you must MAP A URL TO A PARTICULAR VIEW.

And in your case the folio.views.home is mapped. You might need to create a home view to render base.html as homepage.

urls.py

from django.url import include, path
from main.views import home # main is a master app that renders index or home page.

urlpatterns = [
    path('', home, name="index"),
    path('folio/', include('folio.urls'))
]

app_name/views.py

 def home(request):
     return render(request, 'main/base.html', {})

I also encourage todo an app namespacing, in your folio.urls.py before the urlpatterns add this app_name = 'folio' So you can navigate to your folio app home using this url syntax in your main/templates/main/base.html template.

main/templates/main/base.html

 <a href="{% url 'folio:home' %}">Go to folio home page</a>
查看更多
登录 后发表回答