Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 77 ยท URLs and Views

Query Strings, Forms and Request Data

Read query strings, form posts, uploaded files, headers, cookies and JSON bodies in Django views. Learn QueryDict, request.META and how to test it all with RequestFactory.

Every interesting view starts by asking the same question: what did the client send? A search box sends a query string. A sign-up page sends a form. A mobile app sends JSON. A browser also adds headers and cookies to every request without being asked. Django gathers all of this on the HttpRequest object that it hands to your view as the first argument.

In this lesson you will read each kind of input, learn the one data structure that surprises almost everyone (QueryDict), and use RequestFactory to build requests by hand so you can see exactly what a view would receive. If you have not met requests and responses yet, read The Request and Response Cycle first.

Where each piece of data lives

Django parses the raw request into a handful of attributes. Knowing which attribute holds what saves a lot of confusion.

flowchart LR
    R["Incoming HTTP request"] --> G["request.GET<br/>query string"]
    R --> P["request.POST<br/>form-encoded body"]
    R --> F["request.FILES<br/>uploaded files"]
    R --> B["request.body<br/>raw bytes (JSON, XML)"]
    R --> H["request.headers and request.META<br/>headers, server info"]
    R --> C["request.COOKIES<br/>cookies"]

One request, several attributes. The body ends up in POST/FILES or in body, depending on the content type.

Attribute Contains Typical source
request.GET Query-string parameters /search/?q=django
request.POST Text fields of a form <form method="post">
request.FILES Uploaded files <input type="file"> in a multipart form
request.body The raw body as bytes JSON APIs, webhooks
request.headers Request headers (case-insensitive) User-Agent, Accept
request.META Headers plus server and WSGI data REMOTE_ADDR, HTTP_ACCEPT_LANGUAGE
request.COOKIES Cookies as a plain dictionary Cookie: header

The names GET and POST are historical. request.GET holds the query string of any request, even a POST, and request.POST is only filled for form-encoded bodies.

Query strings and QueryDict

The query string is the part of the URL after the question mark. Django parses it into a QueryDict, a dictionary subclass that remembers that one key can appear several times (?tag=web&tag=python). That is the surprise: indexing returns only the last value, and you need getlist() to get them all.

Python Reading request.GET with RequestFactory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Four rules come out of that output:

  • request.GET["q"] raises a KeyError subclass when the key is missing. Prefer request.GET.get("q", default).
  • A single value is always a string. Convert it yourself, and expect that a user can type ?page=abc.
  • getlist("tag") returns every value in order, or an empty list.
  • A QueryDict that comes from a request is immutable. Call .copy() when you need a changeable version, for example to rebuild a pagination link that keeps the other filters.

A safe way to read a number looks like this:

Python
def parse_page(request):
    raw = request.GET.get("page", "1")
    return int(raw) if raw.isdigit() and int(raw) > 0 else 1

Never trust query-string input. The value goes into your ORM filters, templates and redirects, so validate it. The forms lessons show how Django's form classes do this validation for you, and Security in Django explains why unvalidated redirect targets are dangerous.

Form data, files and JSON

When a browser submits <form method="post">, the body is encoded either as application/x-www-form-urlencoded (text only) or as multipart/form-data (needed for files). In both cases Django parses the body into request.POST (a QueryDict) and request.FILES (a dictionary of uploaded file objects).

JSON is different. Django does not parse application/json for you, so request.POST stays empty and you read request.body yourself.

Python POST forms, uploaded files and a JSON body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A real JSON endpoint also has to cope with broken input. Wrap the parsing and answer with 400 Bad Request instead of letting a JSONDecodeError turn into a 500:

Python
import json
from django.http import JsonResponse

def create_item(request):
    try:
        payload = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({"error": "Invalid JSON"}, status=400)
    return JsonResponse({"received": payload}, status=201)

Three details about files are worth remembering. The HTML form needs enctype="multipart/form-data", otherwise the browser sends only the file name. request.FILES["avatar"] is an UploadedFile with .name, .size, .content_type and .read(). And small uploads stay in memory while large ones spool to a temporary file, so use .chunks() for big files instead of .read(). Saving uploads to disk is covered in Static Files and Media.

Headers, META and cookies

request.headers is a case-insensitive mapping of the HTTP headers, so request.headers["user-agent"] and request.headers["User-Agent"] work the same. request.META is the older, lower-level dictionary from the WSGI server. In it, headers are upper-cased, dashes become underscores, and an HTTP_ prefix is added: the Accept-Language header is META["HTTP_ACCEPT_LANGUAGE"]. META also carries values that are not headers at all, such as REMOTE_ADDR (the client's IP address) and REQUEST_METHOD.

Cookies arrive in request.COOKIES as strings, and you set them on a response, not on the request.

Python Headers, META and cookies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two cautions. First, REMOTE_ADDR is the address of whoever connected to Django. Behind a reverse proxy that is the proxy, not the visitor, so the real client address lives in a header such as X-Forwarded-For, which a client can forge. Only trust it when your own proxy sets it. Second, headers are input like any other: never assume that Accept or Referer holds a sensible value.

The attributes request.method, request.path and request.content_type complete the picture. Use request.method to branch between showing a form (GET) and processing it (POST); Handling Forms in Views builds that pattern properly.

Testing views with RequestFactory

RequestFactory creates a request object without running URL routing, middleware or sessions. You call the view as an ordinary Python function:

Python
def search(request):
    q = request.GET.get("q", "")
    return HttpResponse(f"Results for {q!r}")

response = search(RequestFactory().get("/search/", {"q": "django"}))

This is the fastest way to unit-test a view. The trade-off is that nothing else runs: request.user and request.session do not exist unless you attach them yourself. When you want the full stack, including middleware and URL resolution, use the test Client instead. Testing Django Apps compares the two.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A URL is /list/?tag=web&tag=python. What does request.GET['tag'] return?

    Indexing a QueryDict returns the last value for the key. Use request.GET.getlist('tag') to get every value.
  2. 2. A client posts a JSON body with Content-Type: application/json. Where do you read the data?

    Django only fills request.POST for form-encoded bodies. For JSON, request.POST is empty and you parse the raw bytes in request.body yourself.
  3. 3. Why does request.GET.copy() exist?

    QueryDicts built from a request cannot be modified. Copy one when you need to change or rebuild a query string, for example for pagination links.
  4. 4. In request.META, which key holds the Accept-Language header?

    META upper-cases header names, replaces dashes with underscores and adds the HTTP_ prefix. request.headers['Accept-Language'] is the friendlier alternative.
  5. 5. What must an HTML form have for file uploads to reach request.FILES?

    Without multipart encoding the browser sends only the file name as text, so request.FILES stays empty.

Summary

  • request.GET is the parsed query string, request.POST the parsed form body, request.FILES the uploads, and request.body the raw bytes.
  • QueryDict stores several values per key: [key] and .get() return the last one, .getlist() returns all, and request instances are immutable until you .copy() them.
  • Always use .get() with a default and convert strings yourself; never trust input.
  • JSON bodies are not parsed automatically: use json.loads(request.body) and answer 400 for invalid input.
  • request.headers is the friendly header mapping; request.META holds raw WSGI values such as REMOTE_ADDR.
  • Cookies are read from request.COOKIES and written with response.set_cookie().
  • RequestFactory builds requests for fast view tests.

Next, organize your views into reusable classes in Class-Based Views.