Query Strings
Part of the Django Basics section of Coddy's Django journey. Lesson 8 of 23.
The order page always says medium. The size a customer picks can travel in the address, after a question mark: /order/?size=large.
That part is the query string: name=value pairs joined by &. It is not part of the route, so path("search/", ...) matches /search/?q=cake too. The view reads the pairs from request.GET, which works like a dictionary:
def search(request):
word = request.GET.get("q", "")
if len(word) > 30:
word = word[:30]
return HttpResponse(f"Results for {word}").get() takes a default for a missing name; request.GET["q"] would crash instead. Every value arrives as text, and anyone can type anything after the ?, so check a value before you use it.Challenge
EasyMake /order/ read the size from the query string:
?size=largesaysYou ordered a large coffee., and the same forsmallandmedium;- no size, or one the café does not sell like
huge, orders a medium coffee.
Press Run: the preview opens /order/?size=large.
Try it yourself
from django.http import HttpResponse
DRINKS = {
"espresso": {"name": "Espresso", "price": 2.5, "description": "A short, strong shot of coffee."},
"latte": {"name": "Latte", "price": 3.5, "description": "Espresso with lots of steamed milk."},
"flat-white": {"name": "Flat White", "price": 3.75, "description": "Espresso with a thin layer of silky milk."},
"hot-chocolate": {"name": "Hot Chocolate", "price": 3, "description": "Dark chocolate melted into warm milk."},
}
def home(request):
return HttpResponse("<h1>Welcome to Corner Café</h1><p>Fresh coffee and cake every day.</p>")
def about(request):
return HttpResponse("Corner Café opened in 2026.")
def hours(request):
return HttpResponse("Open every day from 8:00 to 18:00.")
def contact(request):
return HttpResponse("Write to us at hello@cornercafe.example.")
def table(request, number):
return HttpResponse(f"<h1>Table {number}</h1>")
def drink(request, slug):
item = DRINKS[slug]
return HttpResponse(f"<h1>{item['name']}</h1><p>{item['description']}</p>")
def order(request):
size = "medium"
return HttpResponse(f"You ordered a {size} coffee.")
All lessons in Django Basics
Practice on your own: Django playground