1 ============================
2 Request and response objects
3 ============================
8 Django uses request and response objects to pass state through the system.
10 When a page is requested, Django creates an ``HttpRequest`` object that
11 contains metadata about the request. Then Django loads the appropriate view,
12 passing the ``HttpRequest`` as the first argument to the view function. Each
13 view is responsible for returning an ``HttpResponse`` object.
15 This document explains the APIs for ``HttpRequest`` and ``HttpResponse``
24 All attributes except ``session`` should be considered read-only.
27 A string representing the full path to the requested page, not including
30 Example: ``"/music/bands/the_beatles/"``
33 A string representing the HTTP method used in the request. This is
34 guaranteed to be uppercase. Example::
36 if request.method == 'GET':
38 elif request.method == 'POST':
42 **New in Django development version**
44 A string representing the current encoding used to decode form submission
45 data (or ``None``, which means the ``DEFAULT_CHARSET`` setting is used).
46 You can write to this attribute to change the encoding used when accessing
47 the form data. Any subsequent attribute accesses (such as reading from
48 ``GET`` or ``POST``) will use the new ``encoding`` value. Useful if you
49 know the form data is not in the ``DEFAULT_CHARSET`` encoding.
52 A dictionary-like object containing all given HTTP GET parameters. See the
53 ``QueryDict`` documentation below.
56 A dictionary-like object containing all given HTTP POST parameters. See the
57 ``QueryDict`` documentation below.
59 It's possible that a request can come in via POST with an empty ``POST``
60 dictionary -- if, say, a form is requested via the POST HTTP method but
61 does not include form data. Therefore, you shouldn't use ``if request.POST``
62 to check for use of the POST method; instead, use ``if request.method ==
65 Note: ``POST`` does *not* include file-upload information. See ``FILES``.
68 For convenience, a dictionary-like object that searches ``POST`` first,
69 then ``GET``. Inspired by PHP's ``$_REQUEST``.
71 For example, if ``GET = {"name": "john"}`` and ``POST = {"age": '34'}``,
72 ``REQUEST["name"]`` would be ``"john"``, and ``REQUEST["age"]`` would be
75 It's strongly suggested that you use ``GET`` and ``POST`` instead of
76 ``REQUEST``, because the former are more explicit.
79 A standard Python dictionary containing all cookies. Keys and values are
84 .. admonition:: Changed in Django development version
86 In previous versions of Django, ``request.FILES`` contained
87 simple ``dict`` objects representing uploaded files. This is
88 no longer true -- files are represented by ``UploadedFile``
89 objects as described below.
91 These ``UploadedFile`` objects will emulate the old-style ``dict``
92 interface, but this is deprecated and will be removed in the next
95 A dictionary-like object containing all uploaded files. Each key in
96 ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each
97 value in ``FILES`` is an ``UploadedFile`` object containing the following
100 * ``read(num_bytes=None)`` -- Read a number of bytes from the file.
101 * ``file_name`` -- The name of the uploaded file.
102 * ``file_size`` -- The size, in bytes, of the uploaded file.
103 * ``chunk()`` -- A generator that yields sequential chunks of data.
105 See `File Uploads`_ for more information.
107 Note that ``FILES`` will only contain data if the request method was POST
108 and the ``<form>`` that posted to the request had
109 ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank
110 dictionary-like object.
112 .. _File Uploads: ../upload_handling/
115 A standard Python dictionary containing all available HTTP headers.
116 Available headers depend on the client and server, but here are some
121 * ``HTTP_ACCEPT_ENCODING``
122 * ``HTTP_ACCEPT_LANGUAGE``
123 * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
124 * ``HTTP_REFERER`` -- The referring page, if any.
125 * ``HTTP_USER_AGENT`` -- The client's user-agent string.
126 * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
127 * ``REMOTE_ADDR`` -- The IP address of the client.
128 * ``REMOTE_HOST`` -- The hostname of the client.
129 * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
130 * ``SERVER_NAME`` -- The hostname of the server.
131 * ``SERVER_PORT`` -- The port of the server.
134 A ``django.contrib.auth.models.User`` object representing the currently
135 logged-in user. If the user isn't currently logged in, ``user`` will be set
136 to an instance of ``django.contrib.auth.models.AnonymousUser``. You
137 can tell them apart with ``is_authenticated()``, like so::
139 if request.user.is_authenticated():
140 # Do something for logged-in users.
142 # Do something for anonymous users.
144 ``user`` is only available if your Django installation has the
145 ``AuthenticationMiddleware`` activated. For more, see
146 `Authentication in Web requests`_.
148 .. _Authentication in Web requests: ../authentication/#authentication-in-web-requests
151 A readable-and-writable, dictionary-like object that represents the current
152 session. This is only available if your Django installation has session
153 support activated. See the `session documentation`_ for full details.
155 .. _`session documentation`: ../sessions/
158 The raw HTTP POST data. This is only useful for advanced processing. Use
162 Not defined by Django itself, but will be read if other code
163 (e.g., a custom middleware class) sets it. When present, this will
164 be used as the root URLconf for the current request, overriding
165 the ``ROOT_URLCONF`` setting. See `How Django processes a
166 request`_ for details.
168 .. _How Django processes a request: ../url_dispatch/#how-django-processes-a-request
174 Returns the GET/POST value for the given key, checking POST first, then
175 GET. Raises ``KeyError`` if the key doesn't exist.
177 This lets you use dictionary-accessing syntax on an ``HttpRequest``
178 instance. Example: ``request["foo"]`` would return ``True`` if either
179 ``request.POST`` or ``request.GET`` had a ``"foo"`` key.
182 Returns ``True`` or ``False``, designating whether ``request.GET`` or
183 ``request.POST`` has the given key.
186 **New in Django development version**
188 Returns the originating host of the request using information from the
189 ``HTTP_X_FORWARDED_HOST`` and ``HTTP_HOST`` headers (in that order). If
190 they don't provide a value, the method uses a combination of
191 ``SERVER_NAME`` and ``SERVER_PORT`` as detailed in `PEP 333`_.
193 .. _PEP 333: http://www.python.org/dev/peps/pep-0333/
195 Example: ``"127.0.0.1:8000"``
198 Returns the ``path``, plus an appended query string, if applicable.
200 Example: ``"/music/bands/the_beatles/?print=true"``
202 ``build_absolute_uri(location)``
203 **New in Django development version**
205 Returns the absolute URI form of ``location``. If no location is provided,
206 the location will be set to ``request.get_full_path()``.
208 If the location is already an absolute URI, it will not be altered.
209 Otherwise the absolute URI is built using the server variables available in
212 Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
215 Returns ``True`` if the request is secure; that is, if it was made with
219 **New in Django development version**
221 Returns ``True`` if the request was made via an ``XMLHttpRequest``, by checking
222 the ``HTTP_X_REQUESTED_WITH`` header for the string ``'XMLHttpRequest'``. The
223 following major JavaScript libraries all send this header:
232 If you write your own XMLHttpRequest call (on the browser side), you'll
233 have to set this header manually if you want ``is_ajax()`` to work.
238 In an ``HttpRequest`` object, the ``GET`` and ``POST`` attributes are instances
239 of ``django.http.QueryDict``. ``QueryDict`` is a dictionary-like
240 class customized to deal with multiple values for the same key. This is
241 necessary because some HTML form elements, notably
242 ``<select multiple="multiple">``, pass multiple values for the same key.
244 ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
245 That means you can't change attributes of ``request.POST`` and ``request.GET``
248 ``QueryDict`` implements all the standard dictionary methods, because it's a
249 subclass of dictionary. Exceptions are outlined here:
251 * ``__getitem__(key)`` -- Returns the value for the given key. If the key
252 has more than one value, ``__getitem__()`` returns the last value.
253 Raises ``django.utils.datastructure.MultiValueDictKeyError`` if the key
254 does not exist. (This is a subclass of Python's standard ``KeyError``,
255 so you can stick to catching ``KeyError``.)
257 * ``__setitem__(key, value)`` -- Sets the given key to ``[value]``
258 (a Python list whose single element is ``value``). Note that this, as
259 other dictionary functions that have side effects, can only be called on
260 a mutable ``QueryDict`` (one that was created via ``copy()``).
262 * ``__contains__(key)`` -- Returns ``True`` if the given key is set. This
263 lets you do, e.g., ``if "foo" in request.GET``.
265 * ``get(key, default)`` -- Uses the same logic as ``__getitem__()`` above,
266 with a hook for returning a default value if the key doesn't exist.
270 * ``setdefault(key, default)`` -- Just like the standard dictionary
271 ``setdefault()`` method, except it uses ``__setitem__`` internally.
273 * ``update(other_dict)`` -- Takes either a ``QueryDict`` or standard
274 dictionary. Just like the standard dictionary ``update()`` method, except
275 it *appends* to the current dictionary items rather than replacing them.
278 >>> q = QueryDict('a=1')
279 >>> q = q.copy() # to make it mutable
280 >>> q.update({'a': '2'})
283 >>> q['a'] # returns the last
286 * ``items()`` -- Just like the standard dictionary ``items()`` method,
287 except this uses the same last-value logic as ``__getitem()__``. For
290 >>> q = QueryDict('a=1&a=2&a=3')
294 * ``values()`` -- Just like the standard dictionary ``values()`` method,
295 except this uses the same last-value logic as ``__getitem()__``. For
298 >>> q = QueryDict('a=1&a=2&a=3')
302 In addition, ``QueryDict`` has the following methods:
304 * ``copy()`` -- Returns a copy of the object, using ``copy.deepcopy()``
305 from the Python standard library. The copy will be mutable -- that is,
306 you can change its values.
308 * ``getlist(key)`` -- Returns the data with the requested key, as a Python
309 list. Returns an empty list if the key doesn't exist. It's guaranteed to
310 return a list of some sort.
312 * ``setlist(key, list_)`` -- Sets the given key to ``list_`` (unlike
315 * ``appendlist(key, item)`` -- Appends an item to the internal list
318 * ``setlistdefault(key, default_list)`` -- Just like ``setdefault``, except
319 it takes a list of values instead of a single value.
321 * ``lists()`` -- Like ``items()``, except it includes all values, as a list,
322 for each member of the dictionary. For example::
324 >>> q = QueryDict('a=1&a=2&a=3')
326 [('a', ['1', '2', '3'])]
328 * ``urlencode()`` -- Returns a string of the data in query-string format.
329 Example: ``"a=2&b=3&b=5"``.
334 Here's an example HTML form and how Django would treat the input::
336 <form action="/foo/bar/" method="post">
337 <input type="text" name="your_name" />
338 <select multiple="multiple" name="bands">
339 <option value="beatles">The Beatles</option>
340 <option value="who">The Who</option>
341 <option value="zombies">The Zombies</option>
343 <input type="submit" />
346 If the user enters ``"John Smith"`` in the ``your_name`` field and selects both
347 "The Beatles" and "The Zombies" in the multiple select box, here's what
348 Django's request object would have::
353 {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']}
354 >>> request.POST['your_name']
356 >>> request.POST['bands']
358 >>> request.POST.getlist('bands')
359 ['beatles', 'zombies']
360 >>> request.POST.get('your_name', 'Adrian')
362 >>> request.POST.get('nonexistent_field', 'Nowhere Man')
368 The ``GET``, ``POST``, ``COOKIES``, ``FILES``, ``META``, ``REQUEST``,
369 ``raw_post_data`` and ``user`` attributes are all lazily loaded. That means
370 Django doesn't spend resources calculating the values of those attributes until
371 your code requests them.
376 In contrast to ``HttpRequest`` objects, which are created automatically by
377 Django, ``HttpResponse`` objects are your responsibility. Each view you write
378 is responsible for instantiating, populating and returning an ``HttpResponse``.
380 The ``HttpResponse`` class lives in the ``django.http`` module.
388 Typical usage is to pass the contents of the page, as a string, to the
389 ``HttpResponse`` constructor::
391 >>> response = HttpResponse("Here's the text of the Web page.")
392 >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
394 But if you want to add content incrementally, you can use ``response`` as a
397 >>> response = HttpResponse()
398 >>> response.write("<p>Here's the text of the Web page.</p>")
399 >>> response.write("<p>Here's another paragraph.</p>")
401 You can add and delete headers using dictionary syntax::
403 >>> response = HttpResponse()
404 >>> response['X-DJANGO'] = "It's the best."
405 >>> del response['X-PHP']
406 >>> response['X-DJANGO']
409 Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist.
414 Finally, you can pass ``HttpResponse`` an iterator rather than passing it
415 hard-coded strings. If you use this technique, follow these guidelines:
417 * The iterator should return strings.
418 * If an ``HttpResponse`` has been initialized with an iterator as its
419 content, you can't use the ``HttpResponse`` instance as a file-like
420 object. Doing so will raise ``Exception``.
425 To set a header in your response, just treat it like a dictionary::
427 >>> response = HttpResponse()
428 >>> response['Pragma'] = 'no-cache'
430 Telling the browser to treat the response as a file attachment
431 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
433 To tell the browser to treat the response as a file attachment, use the
434 ``mimetype`` argument and set the ``Content-Disposition`` header. For example,
435 this is how you might return a Microsoft Excel spreadsheet::
437 >>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
438 >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
440 There's nothing Django-specific about the ``Content-Disposition`` header, but
441 it's easy to forget the syntax, so we've included it here.
446 ``__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE)``
447 Instantiates an ``HttpResponse`` object with the given page content (a
448 string) and MIME type. The ``DEFAULT_CONTENT_TYPE`` is ``'text/html'``.
450 ``content`` can be an iterator or a string. If it's an iterator, it should
451 return strings, and those strings will be joined together to form the
452 content of the response.
454 ``status`` is the `HTTP Status code`_ for the response.
456 **(New in Django development version)** ``content_type`` is an alias for
457 ``mimetype``. Historically, the parameter was only called ``mimetype``,
458 but since this is actually the value included in the HTTP ``Content-Type``
459 header, it can also include the character set encoding, which makes it
460 more than just a MIME type specification. If ``mimetype`` is specified
461 (not ``None``), that value is used. Otherwise, ``content_type`` is used. If
462 neither is given, the ``DEFAULT_CONTENT_TYPE`` setting is used.
464 ``__setitem__(header, value)``
465 Sets the given header name to the given value. Both ``header`` and
466 ``value`` should be strings.
468 ``__delitem__(header)``
469 Deletes the header with the given name. Fails silently if the header
470 doesn't exist. Case-sensitive.
472 ``__getitem__(header)``
473 Returns the value for the given header name. Case-sensitive.
475 ``has_header(header)``
476 Returns ``True`` or ``False`` based on a case-insensitive check for a
477 header with the given name.
479 ``set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)``
480 Sets a cookie. The parameters are the same as in the `cookie Morsel`_
481 object in the Python standard library.
483 * ``max_age`` should be a number of seconds, or ``None`` (default) if
484 the cookie should last only as long as the client's browser session.
485 * ``expires`` should be a string in the format
486 ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``.
487 * Use ``domain`` if you want to set a cross-domain cookie. For example,
488 ``domain=".lawrence.com"`` will set a cookie that is readable by
489 the domains www.lawrence.com, blogs.lawrence.com and
490 calendars.lawrence.com. Otherwise, a cookie will only be readable by
491 the domain that set it.
493 .. _`cookie Morsel`: http://www.python.org/doc/current/lib/morsel-objects.html
495 ``delete_cookie(key, path='/', domain=None)``
496 Deletes the cookie with the given key. Fails silently if the key doesn't
499 Due to the way cookies work, ``path`` and ``domain`` should be the same
500 values you used in ``set_cookie()`` -- otherwise the cookie may not be deleted.
503 Returns the content as a Python string, encoding it from a Unicode object
504 if necessary. Note this is a property, not a method, so use ``r.content``
505 instead of ``r.content()``.
507 ``write(content)``, ``flush()`` and ``tell()``
508 These methods make an ``HttpResponse`` instance a file-like object.
510 .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
512 HttpResponse subclasses
513 -----------------------
515 Django includes a number of ``HttpResponse`` subclasses that handle different
516 types of HTTP responses. Like ``HttpResponse``, these subclasses live in
519 ``HttpResponseRedirect``
520 The constructor takes a single argument -- the path to redirect to. This
521 can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or an
522 absolute URL with no domain (e.g. ``'/search/'``). Note that this returns
523 an HTTP status code 302.
525 ``HttpResponsePermanentRedirect``
526 Like ``HttpResponseRedirect``, but it returns a permanent redirect (HTTP
527 status code 301) instead of a "found" redirect (status code 302).
529 ``HttpResponseNotModified``
530 The constructor doesn't take any arguments. Use this to designate that a
531 page hasn't been modified since the user's last request (status code 304).
533 ``HttpResponseBadRequest``
534 **New in Django development version.**
535 Acts just like ``HttpResponse`` but uses a 400 status code.
537 ``HttpResponseNotFound``
538 Acts just like ``HttpResponse`` but uses a 404 status code.
540 ``HttpResponseForbidden``
541 Acts just like ``HttpResponse`` but uses a 403 status code.
543 ``HttpResponseNotAllowed``
544 Like ``HttpResponse``, but uses a 405 status code. Takes a single,
545 required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
548 Acts just like ``HttpResponse`` but uses a 410 status code.
550 ``HttpResponseServerError``
551 Acts just like ``HttpResponse`` but uses a 500 status code.
556 Returning HTTP error codes in Django is easy. We've already mentioned the
557 ``HttpResponseNotFound``, ``HttpResponseForbidden``,
558 ``HttpResponseServerError``, etc., subclasses; just return an instance of one
559 of those subclasses instead of a normal ``HttpResponse`` in order to signify
560 an error. For example::
562 def my_view(request):
565 return HttpResponseNotFound('<h1>Page not found</h1>')
567 return HttpResponse('<h1>Page was found</h1>')
569 Because 404 errors are by far the most common HTTP error, there's an easier way
570 to handle those errors.
572 The Http404 exception
573 ---------------------
575 When you return an error such as ``HttpResponseNotFound``, you're responsible
576 for defining the HTML of the resulting error page::
578 return HttpResponseNotFound('<h1>Page not found</h1>')
580 For convenience, and because it's a good idea to have a consistent 404 error page
581 across your site, Django provides an ``Http404`` exception. If you raise
582 ``Http404`` at any point in a view function, Django will catch it and return the
583 standard error page for your application, along with an HTTP error code 404.
587 from django.http import Http404
589 def detail(request, poll_id):
591 p = Poll.objects.get(pk=poll_id)
592 except Poll.DoesNotExist:
594 return render_to_response('polls/detail.html', {'poll': p})
596 In order to use the ``Http404`` exception to its fullest, you should create a
597 template that is displayed when a 404 error is raised. This template should be
598 called ``404.html`` and located in the top level of your template tree.
600 Customizing error views
601 -----------------------
603 The 404 (page not found) view
604 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
606 When you raise an ``Http404`` exception, Django loads a special view devoted
607 to handling 404 errors. By default, it's the view
608 ``django.views.defaults.page_not_found``, which loads and renders the template
611 This means you need to define a ``404.html`` template in your root template
612 directory. This template will be used for all 404 errors.
614 This ``page_not_found`` view should suffice for 99% of Web applications, but if
615 you want to override the 404 view, you can specify ``handler404`` in your
618 handler404 = 'mysite.views.my_custom_404_view'
620 Behind the scenes, Django determines the 404 view by looking for ``handler404``.
621 By default, URLconfs contain the following line::
623 from django.conf.urls.defaults import *
625 That takes care of setting ``handler404`` in the current module. As you can see
626 in ``django/conf/urls/defaults.py``, ``handler404`` is set to
627 ``'django.views.defaults.page_not_found'`` by default.
629 Three things to note about 404 views:
631 * The 404 view is also called if Django doesn't find a match after checking
632 every regular expression in the URLconf.
634 * If you don't define your own 404 view -- and simply use the
635 default, which is recommended -- you still have one obligation:
636 you must create a ``404.html`` template in the root of your
637 template directory. The default 404 view will use that template
638 for all 404 errors. The default 404 view will pass one variable
639 to the template: ``request_path``, which is the URL that resulted
642 * The 404 view is passed a ``RequestContext`` and will have access to
643 variables supplied by your ``TEMPLATE_CONTEXT_PROCESSORS`` setting (e.g.,
646 * If ``DEBUG`` is set to ``True`` (in your settings module), then your 404
647 view will never be used, and the traceback will be displayed instead.
649 The 500 (server error) view
650 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
652 Similarly, Django executes special-case behavior in the case of runtime errors
653 in view code. If a view results in an exception, Django will, by default, call
654 the view ``django.views.defaults.server_error``, which loads and renders the
655 template ``500.html``.
657 This means you need to define a ``500.html`` template in your root template
658 directory. This template will be used for all server errors. The default 500
659 view passes no variables to this template and is rendered with an empty
660 ``Context`` to lessen the chance of additional errors.
662 This ``server_error`` view should suffice for 99% of Web applications, but if
663 you want to override the view, you can specify ``handler500`` in your
666 handler500 = 'mysite.views.my_custom_error_view'
668 Behind the scenes, Django determines the error view by looking for ``handler500``.
669 By default, URLconfs contain the following line::
671 from django.conf.urls.defaults import *
673 That takes care of setting ``handler500`` in the current module. As you can see
674 in ``django/conf/urls/defaults.py``, ``handler500`` is set to
675 ``'django.views.defaults.server_error'`` by default.