Django URL Routing
Django Path Handling (URL Routing)
Django maps incoming web addresses to the appropriate view functions through its URL dispatcher. This lets your site know what to show when someone visits a specific page.
Why It Matters
Whenever someone enters a web address (like /about/), Django needs to know which function should respond. Routing links these addresses to the proper Python code.
Main Routing File: urls.py
Each Django project includes a central file for setting up these connections. It's usually located in the main configuration folder (the one with settings.py).
Example structure:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')), # Linking to app-level routes
] path() Breakdown
Each path() does the job of pairing a web link to a function.
Syntax:
path('route/', handler, name='optional_name')- 'route/' – the web address (without domain).
- handler – the designated view that crafts and delivers the reply to a given request.
- name – an optional tag used to reference the URL elsewhere (like in templates).
App-Specific Routing
Inside each app, you can create its own urls.py for better separation.
Example in an app named home:
# home/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='home_index'),
path('about/', views.about, name='home_about'),
]This approach organizes your URL patterns neatly, making route definitions more maintainable and isolated.
Linking Everything Together
To use an app’s routes, go back to the project-level urls.py and include them:
path('', include('home.urls'))Now when someone goes to /about/, Django sends that to views.about.
Example View Code
Inside views.py of your app:
from django.http import HttpResponse
def index(request):
return HttpResponse("Welcome to the homepage!")
def about(request):
Return HttpResponse("About us section.")Dynamic Segments
Angle brackets allow dynamic segments within URLs to be extracted as parameters.
path('user/<int:id>/', views.profile)This sends id as a number into the profile() view.
Example:
def profile(request, id):
Return HttpResponse(f"Profile number {id}") Summary
- Routes map URLs to functions.
- Each app can manage its own routing file.
- Dynamic parts let you handle pages like user profiles or posts.
- Everything connects together through the project’s main router.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand HTML Tutorial visually:
What You'll Learn:
- 📌 URL Routing - Python Django Tutorial 3
- 📌 Try DJANGO Tutorial - 13 - URL Routing and Requests