URL Configuration Basics
Django uses a URL configuration system (URLconf) to map URLs to views. Each URL pattern is defined using the path() function in urls.py. The URL router is the entry point for every request — it decides which view handles which URL.
How URL Routing Works
When a request comes in, Django checks the ROOT_URLCONF setting to find the main urls.py. It then goes through each URL pattern in order until it finds a match. If matched, Django calls the associated view function. If no match is found, Django returns a 404 error.
QuerySets are LAZY — no DB hit until evaluated.
URL Pattern Basics
- path(route, view, name) — Define a URL pattern
- route — URL string like 'about/' or 'blog/<int:id>/'
- view — The function or class that handles the request
- name — A unique name for reversing URLs in templates
- include() — Include another app's urls.py
- Always end routes with a trailing slash: 'about/' not 'about'
- Root URL '' maps to the homepage
URL Configuration
# mysite/urls.py — Project-level URL configuration
# from django.contrib import admin
# from django.urls import path, include
# urlpatterns = [
# path('admin/', admin.site.urls), # Admin panel
# path('blog/', include('blog.urls')), # Include blog app URLs
# path('', include('pages.urls')), # Include pages app URLs
# ]
# blog/urls.py — App-level URL configuration
# from django.urls import path
# from . import views
# app_name = 'blog' # Namespace for this app
# urlpatterns = [
# path('', views.blog_home, name='home'),
# path('<int:pk>/', views.blog_detail, name='detail'),
# path('create/', views.blog_create, name='create'),
# ]Tip
Tip
Use render() shortcut instead of HttpResponse for template rendering. It automatically uses RequestContext for template tags.
Common Mistake
Warning
Doing database queries inside templates. Keep business logic in views or models, not templates. Templates should only display data.
Practice Task
Note
(1) Create a view that returns an HttpResponse. (2) Create one using render() with a template. (3) Pass context data to the template.
Quick Quiz
Key Takeaways
- Django uses a URL configuration system (URLconf) to map URLs to views.
- path(route, view, name) — Define a URL pattern
- route — URL string like 'about/' or 'blog/<int:id>/'
- view — The function or class that handles the request