Previously I showed how to set up Django and install on your development environment. Next we need to make it really useful, and that means responding to user requests.
But what actually happens when someone visits a page on your Django site?
Let's look at how Django works under the hood, from incoming request to outgoing response.
It doesn't matter if you're building a blog, a dashboard, or an API, understanding this flow is fundamental for structure in your apps, and to help you debug faster.
What Happens When a User Visits Your Site?
When a user visits a URL on your Django site, here's what happens behind the scenes:
- Django receives the HTTP request from the browser.
- It checks the top-level URL configuration in
myproject/urls.py
. - Django tries to match the requested URL pattern to one of the defined
path()
entries. - If matched, it either routes directly to a view or includes another URLconf from an app (for modular structure).
- App-level
urls.py
continues matching any remaining part of the URL. - Once a matching pattern is found, it points to a view function.
- The view function runs your Python logic (e.g., database queries, calculations).
- The view returns an
HttpResponse
object—HTML, JSON, a redirect, or an error. - Django sends this response back to the user's browser.
Handling Path Variables (e.g., /greet/Alice/
)
Sometimes you want to use part of the URL as a variable, such as a name or ID.
Step 1: Add a view in greetings/views.py
from django.http import HttpResponse
def home(request):
html_content = "Welcome to the App!
This is the homepage.
"
return HttpResponse(html_content)
def personalized_greeting(request, name):
html_content = f"Hello, {name.capitalize()}!
Nice to meet you.
"
return HttpResponse(html_content)
Step 2: Add a URL pattern in greetings/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('/', views.personalized_greeting, name='personalized_greeting'),
]
<str:name>
captures part of the URL and passes it to the view.- Other converters:
int:
,slug:
,uuid:
,path:
Handling Query Parameters (e.g., /search?q=django
)
Query parameters come after the ?
in a URL. They're not part of the path matching.
View example in greetings/views.py
def search(request):
query = request.GET.get('q', '')
page = request.GET.get('page', '1')
html_content = "Search Results
"
if query:
html_content += f"You searched for: {query}
"
else:
html_content += "Please provide a search term using ?q=...
"
html_content += f"Showing page: {page}
"
return HttpResponse(html_content)
URL pattern
path('search/', views.search, name='search'),
Redirecting the User
Sometimes you want to send the user to another page (e.g., after submitting a form or accessing a shortcut URL).
View example
from django.http import HttpResponseRedirect
from django.urls import reverse
def go_home(request):
return HttpResponseRedirect(reverse('home'))
Or shorter, using redirect
:
from django.shortcuts import redirect
def go_home(request):
return redirect('home')
URL pattern
path('go-home/', views.go_home, name='go_home'),
Returning a 404 Not Found
To manually raise a 404 (e.g., when a record doesn’t exist), use:
from django.http import Http404
def show_profile(request, username):
allowed_users = ['alice', 'bob', 'carol']
if username not in allowed_users:
raise Http404("User not found")
html_content = f"Profile of {username.capitalize()}
"
return HttpResponse(html_content)
URL pattern
path('profile//', views.show_profile, name='show_profile'),
If you want to customize the 404 page, create a 404.html
template and Django will render it automatically when a 404 is raised.
Testing the Server
Start your server with:
python3 manage.py runserver
Try these in your browser:
http://127.0.0.1:8000/greetings/Alice/
http://127.0.0.1:8000/greetings/search/?q=django
http://127.0.0.1:8000/greetings/go-home/
http://127.0.0.1:8000/greetings/profile/zorg/
(should show a 404)