URLs & Routing
Each app defines its own urls.py mapping a path pattern
to a view. The project's root urls.py then
include()s each app's URLs under a prefix.
Example: one app's URLs, included into the project
# blog/urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
]
# myproject/urls.py
from django.urls import include, path
urlpatterns = [
path('blog/', include('blog.urls')),
]
Requests to /blog/ are routed to the post_list view.
This is exactly how this actual platform's own URLs are structured, each app owns its own urls.py (tutorials, courses,
marketplace, each independently), and the root urls.py
mounts every one of them under its own prefix. app_name
matters for a real practical reason: it lets templates reference
{% url 'blog:post_list' %} unambiguously, even if a
different app also happens to have a view named post_list.
# blog/urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
]
# myproject/urls.py
from django.urls import include, path
urlpatterns = [
path('blog/', include('blog.urls')),
]
Requests to /blog/ are routed to the post_list view.