Views & URLs
Map web addresses to Python functions that respond.
What you will learn
- Write a view function
- Connect it to a URL
- Return a response
How a page gets built
When someone visits a page on your site, Django follows a fixed path to decide what to send back. Knowing this request → response flow makes everything else click into place.
- The browser asks for a web address (a URL), for example
/or/about. - Django looks down its list of URL patterns until it finds one that matches.
- That match points to a view — a Python function — which Django runs, handing it the
request. - The view does its work and returns a response (some text, or a full HTML page).
- Django sends that response back to the browser, which shows it to the user.
A view is a Python function
A view is just a normal Python function that takes the incoming request and returns something to show. The simplest one returns a short piece of text:
# blog/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to my blog!")Line by line: we import HttpResponse (Django’s way of sending a reply). We define home, which receives request (information about who is visiting). It returns an HttpResponse holding the text the visitor will see. That is a complete, working view.
Connect a URL to it
A view does nothing on its own — you must tell Django which web address should run it. You do that in a urls.py file by adding the view to the urlpatterns list:
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
]Here path() links an address to a view. The first argument "" is the address (empty means the app’s home page). The second, views.home, is the view function to run. The third, name="home", is a nickname you can use elsewhere to refer to this URL without re-typing the address.
Finally, the project needs to know about the app’s URLs. In the main mysite/urls.py you include the app’s url file so its patterns are added to the site:
# mysite/urls.py — include the app’s urls
from django.urls import path, include
urlpatterns = [
path("", include("blog.urls")),
]include("blog.urls") tells Django: "for addresses starting here, hand off to the blog app’s URL list." Now visiting / runs home and the browser shows your message.
Note: Output (in the browser at http://127.0.0.1:8000):
Welcome to my blog!
The URL matched path("") → Django ran the home view → the view returned the text → the browser displayed it.
Tip: A view always takes request as its first argument and returns a response. Most of the time you’ll return a rendered template instead of plain text — that’s next.
Q. What is the first argument every Django view receives?
✍️ Practice
- Create a
homeview that returns a message and wire its URL. - Add an
/aboutURL and view.
🏠 Homework
- Create three pages (home, about, contact) each with a view and URL.