djangourlconf

Django website loads with empty root urls.py file


I know it's feels like elementary, and yet I can't come up with a clean solution based on doc only. I have the following project structure (I omit files like models.py, forms.py for the purpose of keeping the question concise)

As you see, my goal is to have a separate urls.py file for each app, and then assemble them into root urls.py (depicted at the same level as settings.py in the list above). The problem is that my root urls.py is EMPTY (!!!) now, and the site still loads the home page !!! What am I doing wrong ??? See the details below:

settings.py:

ROOT_URLCONF = 'urls'

hellow_world urls.py:

urlpatterns = [
    url(r'^$', views.home , name = 'home'),
]

root urls.py - empty !

manage.py:

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Solution

  • Use include() to include more urls:

    # your main urls.py file
    from django.conf.urls import include, url
    
    urlpatterns = [
        url(r'^myapp1/', include('myapp1.urls')),
        url(r'^myapp2/', include('myapp2.urls')),
    ]
    

    And:

    # myapp1/urls.py
    from django.conf.urls import url
    
    from . import views
    
    app_name = 'myapp1'
    urlpatterns = [
        url(r'^$', views.IndexView.as_view(), name='index'),
        url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
        #...
    ]