← Back to Chapters

Understanding urls.py

? Understanding urls.py

? Quick Overview

The urls.py file is responsible for URL routing in Django. It maps incoming HTTP requests to the appropriate view functions based on the requested URL. Django supports two levels of URL configuration: project-level and app-level.

? Key Concepts

  • URL routing connects URLs to views
  • Project-level URLs act as the main entry point
  • App-level URLs handle modular routing
  • include() enables reusable URL patterns

? Project-Level URLs

The project-level urls.py is located in the main project directory. It includes URL configurations from individual apps.

? View Code Example
// Project-level urls.py configuration
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]

This setup forwards all /blog/ requests to the blog app’s URL configuration.

? App-Level URLs

Each Django app can define its own urls.py containing routes specific to that app.

? View Code Example
// App-level urls.py for blog app
from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('post/<int:id>/', views.post_detail, name='post_detail'),
]

? Using include()

The include() function helps modularize URL routing by delegating URL handling to apps.

? View Code Example
// Including multiple apps at project level
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
path('shop/', include('shop.urls')),
]

? Explanation

  • Project-Level URLs: Central routing file that includes app URLs.
  • App-Level URLs: App-specific routes mapped to views.
  • Modular Routing: Makes large projects manageable.

? Interactive Example (URL Flow)

// URL request flow demonstration
Browser Request → project urls.py → include() → app urls.py → view function

⚡ Live Path Simulator

Type a URL path to see how Django resolves it:

yourdomain.com/
1. Project URLs: Checking urlpatterns...
2. include(): Handing off to blog.urls...
3. App URLs: Finding view...
Result: Waiting for input...

? Use Cases

  • Large multi-app Django projects
  • Clean separation of concerns
  • Scalable URL management

✅ Tips & Best Practices

  • Keep app URLs focused and modular
  • Always use named URL patterns
  • Avoid placing app logic in project URLs

? Try It Yourself

  • Create a new Django app and add urls.py
  • Include it in the project-level URLs
  • Test dynamic URL parameters in the browser