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 **New in Django development version**
176 Returns the originating host of the request using information from the
177 ``HTTP_X_FORWARDED_HOST`` and ``HTTP_HOST`` headers (in that order). If
178 they don't provide a value, the method uses a combination of
179 ``SERVER_NAME`` and ``SERVER_PORT`` as detailed in `PEP 333`_.
181 .. _PEP 333: http://www.python.org/dev/peps/pep-0333/
183 Example: ``"127.0.0.1:8000"``
186 Returns the ``path``, plus an appended query string, if applicable.
188 Example: ``"/music/bands/the_beatles/?print=true"``
190 ``build_absolute_uri(location)``
191 **New in Django development version**
193 Returns the absolute URI form of ``location``. If no location is provided,
194 the location will be set to ``request.get_full_path()``.
196 If the location is already an absolute URI, it will not be altered.
197 Otherwise the absolute URI is built using the server variables available in
200 Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
203 Returns ``True`` if the request is secure; that is, if it was made with
207 **New in Django development version**
209 Returns ``True`` if the request was made via an ``XMLHttpRequest``, by checking
210 the ``HTTP_X_REQUESTED_WITH`` header for the string ``'XMLHttpRequest'``. The
211 following major JavaScript libraries all send this header:
220 If you write your own XMLHttpRequest call (on the browser side), you'll
221 have to set this header manually if you want ``is_ajax()`` to work.
226 In an ``HttpRequest`` object, the ``GET`` and ``POST`` attributes are instances
227 of ``django.http.QueryDict``. ``QueryDict`` is a dictionary-like
228 class customized to deal with multiple values for the same key. This is
229 necessary because some HTML form elements, notably
230 ``<select multiple="multiple">``, pass multiple values for the same key.
232 ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
233 That means you can't change attributes of ``request.POST`` and ``request.GET``
236 ``QueryDict`` implements all the standard dictionary methods, because it's a
237 subclass of dictionary. Exceptions are outlined here:
239 * ``__getitem__(key)`` -- Returns the value for the given key. If the key
240 has more than one value, ``__getitem__()`` returns the last value.
241 Raises ``django.utils.datastructure.MultiValueDictKeyError`` if the key
242 does not exist. (This is a subclass of Python's standard ``KeyError``,
243 so you can stick to catching ``KeyError``.)
245 * ``__setitem__(key, value)`` -- Sets the given key to ``[value]``
246 (a Python list whose single element is ``value``). Note that this, as
247 other dictionary functions that have side effects, can only be called on
248 a mutable ``QueryDict`` (one that was created via ``copy()``).
250 * ``__contains__(key)`` -- Returns ``True`` if the given key is set. This
251 lets you do, e.g., ``if "foo" in request.GET``.
253 * ``get(key, default)`` -- Uses the same logic as ``__getitem__()`` above,
254 with a hook for returning a default value if the key doesn't exist.
258 * ``setdefault(key, default)`` -- Just like the standard dictionary
259 ``setdefault()`` method, except it uses ``__setitem__`` internally.
261 * ``update(other_dict)`` -- Takes either a ``QueryDict`` or standard
262 dictionary. Just like the standard dictionary ``update()`` method, except
263 it *appends* to the current dictionary items rather than replacing them.
266 >>> q = QueryDict('a=1')
267 >>> q = q.copy() # to make it mutable
268 >>> q.update({'a': '2'})
271 >>> q['a'] # returns the last
274 * ``items()`` -- Just like the standard dictionary ``items()`` method,
275 except this uses the same last-value logic as ``__getitem()__``. For
278 >>> q = QueryDict('a=1&a=2&a=3')
282 * ``values()`` -- Just like the standard dictionary ``values()`` method,
283 except this uses the same last-value logic as ``__getitem()__``. For
286 >>> q = QueryDict('a=1&a=2&a=3')
290 In addition, ``QueryDict`` has the following methods:
292 * ``copy()`` -- Returns a copy of the object, using ``copy.deepcopy()``
293 from the Python standard library. The copy will be mutable -- that is,
294 you can change its values.
296 * ``getlist(key)`` -- Returns the data with the requested key, as a Python
297 list. Returns an empty list if the key doesn't exist. It's guaranteed to
298 return a list of some sort.
300 * ``setlist(key, list_)`` -- Sets the given key to ``list_`` (unlike
303 * ``appendlist(key, item)`` -- Appends an item to the internal list
306 * ``setlistdefault(key, default_list)`` -- Just like ``setdefault``, except
307 it takes a list of values instead of a single value.
309 * ``lists()`` -- Like ``items()``, except it includes all values, as a list,
310 for each member of the dictionary. For example::
312 >>> q = QueryDict('a=1&a=2&a=3')
314 [('a', ['1', '2', '3'])]
316 * ``urlencode()`` -- Returns a string of the data in query-string format.
317 Example: ``"a=2&b=3&b=5"``.
322 Here's an example HTML form and how Django would treat the input::
324 <form action="/foo/bar/" method="post">
325 <input type="text" name="your_name" />
326 <select multiple="multiple" name="bands">
327 <option value="beatles">The Beatles</option>
328 <option value="who">The Who</option>
329 <option value="zombies">The Zombies</option>
331 <input type="submit" />
334 If the user enters ``"John Smith"`` in the ``your_name`` field and selects both
335 "The Beatles" and "The Zombies" in the multiple select box, here's what
336 Django's request object would have::
341 {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']}
342 >>> request.POST['your_name']
344 >>> request.POST['bands']
346 >>> request.POST.getlist('bands')
347 ['beatles', 'zombies']
348 >>> request.POST.get('your_name', 'Adrian')
350 >>> request.POST.get('nonexistent_field', 'Nowhere Man')
356 The ``GET``, ``POST``, ``COOKIES``, ``FILES``, ``META``, ``REQUEST``,
357 ``raw_post_data`` and ``user`` attributes are all lazily loaded. That means
358 Django doesn't spend resources calculating the values of those attributes until
359 your code requests them.
364 In contrast to ``HttpRequest`` objects, which are created automatically by
365 Django, ``HttpResponse`` objects are your responsibility. Each view you write
366 is responsible for instantiating, populating and returning an ``HttpResponse``.
368 The ``HttpResponse`` class lives in the ``django.http`` module.
376 Typical usage is to pass the contents of the page, as a string, to the
377 ``HttpResponse`` constructor::
379 >>> response = HttpResponse("Here's the text of the Web page.")
380 >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
382 But if you want to add content incrementally, you can use ``response`` as a
385 >>> response = HttpResponse()
386 >>> response.write("<p>Here's the text of the Web page.</p>")
387 >>> response.write("<p>Here's another paragraph.</p>")
389 You can add and delete headers using dictionary syntax::
391 >>> response = HttpResponse()
392 >>> response['X-DJANGO'] = "It's the best."
393 >>> del response['X-PHP']
394 >>> response['X-DJANGO']
397 Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist.
402 Finally, you can pass ``HttpResponse`` an iterator rather than passing it
403 hard-coded strings. If you use this technique, follow these guidelines:
405 * The iterator should return strings.
406 * If an ``HttpResponse`` has been initialized with an iterator as its
407 content, you can't use the ``HttpResponse`` instance as a file-like
408 object. Doing so will raise ``Exception``.
413 To set a header in your response, just treat it like a dictionary::
415 >>> response = HttpResponse()
416 >>> response['Pragma'] = 'no-cache'
418 Telling the browser to treat the response as a file attachment
419 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
421 To tell the browser to treat the response as a file attachment, use the
422 ``mimetype`` argument and set the ``Content-Disposition`` header. For example,
423 this is how you might return a Microsoft Excel spreadsheet::
425 >>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
426 >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
428 There's nothing Django-specific about the ``Content-Disposition`` header, but
429 it's easy to forget the syntax, so we've included it here.
434 ``__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE)``
435 Instantiates an ``HttpResponse`` object with the given page content (a
436 string) and MIME type. The ``DEFAULT_CONTENT_TYPE`` is ``'text/html'``.
438 ``content`` can be an iterator or a string. If it's an iterator, it should
439 return strings, and those strings will be joined together to form the
440 content of the response.
442 ``status`` is the `HTTP Status code`_ for the response.
444 **(New in Django development version)** ``content_type`` is an alias for
445 ``mimetype``. Historically, the parameter was only called ``mimetype``,
446 but since this is actually the value included in the HTTP ``Content-Type``
447 header, it can also include the character set encoding, which makes it
448 more than just a MIME type specification. If ``mimetype`` is specified
449 (not ``None``), that value is used. Otherwise, ``content_type`` is used. If
450 neither is given, the ``DEFAULT_CONTENT_TYPE`` setting is used.
452 ``__setitem__(header, value)``
453 Sets the given header name to the given value. Both ``header`` and
454 ``value`` should be strings.
456 ``__delitem__(header)``
457 Deletes the header with the given name. Fails silently if the header
458 doesn't exist. Case-sensitive.
460 ``__getitem__(header)``
461 Returns the value for the given header name. Case-sensitive.
463 ``has_header(header)``
464 Returns ``True`` or ``False`` based on a case-insensitive check for a
465 header with the given name.
467 ``set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)``
468 Sets a cookie. The parameters are the same as in the `cookie Morsel`_
469 object in the Python standard library.
471 * ``max_age`` should be a number of seconds, or ``None`` (default) if
472 the cookie should last only as long as the client's browser session.
473 * ``expires`` should be a string in the format
474 ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``.
475 * Use ``domain`` if you want to set a cross-domain cookie. For example,
476 ``domain=".lawrence.com"`` will set a cookie that is readable by
477 the domains www.lawrence.com, blogs.lawrence.com and
478 calendars.lawrence.com. Otherwise, a cookie will only be readable by
479 the domain that set it.
481 .. _`cookie Morsel`: http://www.python.org/doc/current/lib/morsel-objects.html
483 ``delete_cookie(key, path='/', domain=None)``
484 Deletes the cookie with the given key. Fails silently if the key doesn't
487 Due to the way cookies work, ``path`` and ``domain`` should be the same
488 values you used in ``set_cookie()`` -- otherwise the cookie may not be deleted.
491 Returns the content as a Python string, encoding it from a Unicode object
492 if necessary. Note this is a property, not a method, so use ``r.content``
493 instead of ``r.content()``.
495 ``write(content)``, ``flush()`` and ``tell()``
496 These methods make an ``HttpResponse`` instance a file-like object.
498 .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
500 HttpResponse subclasses
501 -----------------------
503 Django includes a number of ``HttpResponse`` subclasses that handle different
504 types of HTTP responses. Like ``HttpResponse``, these subclasses live in
507 ``HttpResponseRedirect``
508 The constructor takes a single argument -- the path to redirect to. This
509 can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or an
510 absolute URL with no domain (e.g. ``'/search/'``). Note that this returns
511 an HTTP status code 302.
513 ``HttpResponsePermanentRedirect``
514 Like ``HttpResponseRedirect``, but it returns a permanent redirect (HTTP
515 status code 301) instead of a "found" redirect (status code 302).
517 ``HttpResponseNotModified``
518 The constructor doesn't take any arguments. Use this to designate that a
519 page hasn't been modified since the user's last request (status code 304).
521 ``HttpResponseBadRequest``
522 **New in Django development version.**
523 Acts just like ``HttpResponse`` but uses a 400 status code.
525 ``HttpResponseNotFound``
526 Acts just like ``HttpResponse`` but uses a 404 status code.
528 ``HttpResponseForbidden``
529 Acts just like ``HttpResponse`` but uses a 403 status code.
531 ``HttpResponseNotAllowed``
532 Like ``HttpResponse``, but uses a 405 status code. Takes a single,
533 required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
536 Acts just like ``HttpResponse`` but uses a 410 status code.
538 ``HttpResponseServerError``
539 Acts just like ``HttpResponse`` but uses a 500 status code.
544 Returning HTTP error codes in Django is easy. We've already mentioned the
545 ``HttpResponseNotFound``, ``HttpResponseForbidden``,
546 ``HttpResponseServerError``, etc., subclasses; just return an instance of one
547 of those subclasses instead of a normal ``HttpResponse`` in order to signify
548 an error. For example::
550 def my_view(request):
553 return HttpResponseNotFound('<h1>Page not found</h1>')
555 return HttpResponse('<h1>Page was found</h1>')
557 Because 404 errors are by far the most common HTTP error, there's an easier way
558 to handle those errors.
560 The Http404 exception
561 ---------------------
563 When you return an error such as ``HttpResponseNotFound``, you're responsible
564 for defining the HTML of the resulting error page::
566 return HttpResponseNotFound('<h1>Page not found</h1>')
568 For convenience, and because it's a good idea to have a consistent 404 error page
569 across your site, Django provides an ``Http404`` exception. If you raise
570 ``Http404`` at any point in a view function, Django will catch it and return the
571 standard error page for your application, along with an HTTP error code 404.
575 from django.http import Http404
577 def detail(request, poll_id):
579 p = Poll.objects.get(pk=poll_id)
580 except Poll.DoesNotExist:
582 return render_to_response('polls/detail.html', {'poll': p})
584 In order to use the ``Http404`` exception to its fullest, you should create a
585 template that is displayed when a 404 error is raised. This template should be
586 called ``404.html`` and located in the top level of your template tree.
588 Customizing error views
589 -----------------------
591 The 404 (page not found) view
592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
594 When you raise an ``Http404`` exception, Django loads a special view devoted
595 to handling 404 errors. By default, it's the view
596 ``django.views.defaults.page_not_found``, which loads and renders the template
599 This means you need to define a ``404.html`` template in your root template
600 directory. This template will be used for all 404 errors.
602 This ``page_not_found`` view should suffice for 99% of Web applications, but if
603 you want to override the 404 view, you can specify ``handler404`` in your
606 handler404 = 'mysite.views.my_custom_404_view'
608 Behind the scenes, Django determines the 404 view by looking for ``handler404``.
609 By default, URLconfs contain the following line::
611 from django.conf.urls.defaults import *
613 That takes care of setting ``handler404`` in the current module. As you can see
614 in ``django/conf/urls/defaults.py``, ``handler404`` is set to
615 ``'django.views.defaults.page_not_found'`` by default.
617 Three things to note about 404 views:
619 * The 404 view is also called if Django doesn't find a match after checking
620 every regular expression in the URLconf.
622 * If you don't define your own 404 view -- and simply use the
623 default, which is recommended -- you still have one obligation:
624 you must create a ``404.html`` template in the root of your
625 template directory. The default 404 view will use that template
626 for all 404 errors. The default 404 view will pass one variable
627 to the template: ``request_path``, which is the URL that resulted
630 * The 404 view is passed a ``RequestContext`` and will have access to
631 variables supplied by your ``TEMPLATE_CONTEXT_PROCESSORS`` setting (e.g.,
634 * If ``DEBUG`` is set to ``True`` (in your settings module), then your 404
635 view will never be used, and the traceback will be displayed instead.
637 The 500 (server error) view
638 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
640 Similarly, Django executes special-case behavior in the case of runtime errors
641 in view code. If a view results in an exception, Django will, by default, call
642 the view ``django.views.defaults.server_error``, which loads and renders the
643 template ``500.html``.
645 This means you need to define a ``500.html`` template in your root template
646 directory. This template will be used for all server errors. The default 500
647 view passes no variables to this template and is rendered with an empty
648 ``Context`` to lessen the chance of additional errors.
650 This ``server_error`` view should suffice for 99% of Web applications, but if
651 you want to override the view, you can specify ``handler500`` in your
654 handler500 = 'mysite.views.my_custom_error_view'
656 Behind the scenes, Django determines the error view by looking for ``handler500``.
657 By default, URLconfs contain the following line::
659 from django.conf.urls.defaults import *
661 That takes care of setting ``handler500`` in the current module. As you can see
662 in ``django/conf/urls/defaults.py``, ``handler500`` is set to
663 ``'django.views.defaults.server_error'`` by default.