URLs & Views

A view is just a Python function that takes a request and returns a response. A URL pattern decides which view runs for a given address. Together, they're the entire journey from "someone visits a URL" to "some Python code runs."

Your first view

A view function takes an HttpRequest and must return an HttpResponse:

Python blog/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello from Django!")

On its own, this function is unreachable — nothing connects a URL to it yet. That's the job of a URL pattern.

Wiring up a URL

Each app gets its own urls.py (you create this file — it's not generated automatically), which the project's main urls.py then includes:

Python blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]
Python mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]
Visiting http://127.0.0.1:8000/
Hello from Django!

include('blog.urls') hands off any URL matching that prefix to the app's own urls.py — this is how a project stays organized as more apps get added, each owning its own slice of the URL space instead of one giant file.

URL parameters

A URL pattern can capture part of the address and pass it straight into the view as an argument:

Python blog/urls.py
urlpatterns = [
    path('', views.home, name='home'),
    path('post/<int:post_id>/', views.post_detail, name='post_detail'),
]
Python blog/views.py
def post_detail(request, post_id):
    return HttpResponse(f"Showing post #{post_id}")
Visiting http://127.0.0.1:8000/post/7/
Showing post #7

<int:post_id> matches only digits and converts them to a Python int before calling the view — /post/7/ matches and calls post_detail(request, post_id=7), but /post/abc/ wouldn't match this pattern at all.

Note: returning a bare string with HttpResponse is fine for learning, but no real Django view builds HTML this way — the next lesson, Templates, covers the actual mechanism for rendering a full page, keeping HTML out of your Python files entirely.