Query String Values Arrive in request.GET as Strings, and Missing Keys Raise Unless You Use get()

In progress Django

Everything after ? in a URL is the query string: /tasks/?category=gardening carries category with the value "gardening". Django exposes it as request.GET, a dictionary-like QueryDict whose values are always strings, possibly several per key. Reading a key that wasn't sent with request.GET["category"] raises MultiValueDictKeyError (a KeyError), which becomes a 500 error; optional parameters must be read with .get() and converted explicitly.

Reading an Optional Filter

def index(request):
    context = {"categories": Category.objects.order_by("name")}
    tasks = Task.objects.all()

    category_slug = request.GET.get("category")        # None if absent
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        context["category"] = category
        tasks = tasks.filter(category=category)

    context["tasks"] = tasks
    return render(request, "tasks/index.html", context)

Everything Is a String

Query string request.GET... Value
?page=2 .get("page") "2", not 2
?done=false .get("done") "false", which is truthy
?tag=a&tag=b .get("tag") / .getlist("tag") "b" / ["a", "b"]
(absent) .get("page", "1") the default

Where the Other Request Data Lives

Path parameters arrive as view arguments (via converters), form fields of a POST in request.POST, uploaded files in request.FILES, and a JSON body in request.body (to parse with json.loads). request.method says which applies.

References

Review cards

Flashcard Why should you use `.get()` to read optional parameters from `request.GET`?

Using .get() prevents MultiValueDictKeyError when the key is missing from the query string, ensuring your application handles missing parameters gracefully.

Flashcard What does request.GET.get('done') return for ?done=false?

The string 'false', which is truthy. Query values are always strings: compare or convert them explicitly, or validate the query string with a form.