← Back to all tutorials

URLs and Views

Map URLs to view functions — understand Django URL routing and create your first view that returns an HTTP response.

URLs and Views

When a user visits a URL, Django looks through the URL patterns to find a match, then calls the associated view function to handle the request.

The URL Dispatcher

# djangoblog/urls.py
from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.homepage, name='homepage'),
    path('about/', views.about, name='about'),
]

Creating Views

# djangoblog/views.py
from django.http import HttpResponse

def homepage(request):
    return HttpResponse('Welcome to the Blog!')

def about(request):
    return HttpResponse('About page')

How URL Routing Works

User visits /about/
    ↓
Django checks urlpatterns:
    '' → homepage ✗
    'about/' → about ✓
    ↓
Calls about(request)
    ↓
Returns HttpResponse('About page')

URL Pattern Syntax

# path(route, view, name)
path('', views.homepage, name='homepage')
#     │         │              │
#     │         │              └── Name for reverse lookups
#     │         └── The view function to call
#     └── The URL pattern to match

Key Takeaways

  • Django matches URLs from the urlpatterns list in order
  • Each path() maps a URL pattern to a view function
  • View functions receive a request object and return an HttpResponse
  • The name parameter lets you reference URLs by name instead of hardcoding paths