Fixed #8545: Corrected typo in request/response docs
[django.git] / docs / ref / request-response.txt
blob6415a7d335e5921a4ba5eea48f0862f7df7f874b
1 .. _ref-request-response:
3 ============================
4 Request and response objects
5 ============================
7 .. module:: django.http
8    :synopsis: Classes dealing with HTTP requests and responses.
10 Quick overview
11 ==============
13 Django uses request and response objects to pass state through the system.
15 When a page is requested, Django creates an :class:`HttpRequest` object that
16 contains metadata about the request. Then Django loads the appropriate view,
17 passing the :class:`HttpRequest` as the first argument to the view function. Each
18 view is responsible for returning an :class:`HttpResponse` object.
20 This document explains the APIs for :class:`HttpRequest` and :class:`HttpResponse`
21 objects.
23 HttpRequest objects
24 ===================
26 .. class:: HttpRequest
28 Attributes
29 ----------
31 All attributes except ``session`` should be considered read-only.
33 .. attribute:: HttpRequest.path
35    A string representing the full path to the requested page, not including
36    the domain.
38    Example: ``"/music/bands/the_beatles/"``
40 .. attribute:: HttpRequest.method
42     A string representing the HTTP method used in the request. This is
43     guaranteed to be uppercase. Example::
45         if request.method == 'GET':
46             do_something()
47         elif request.method == 'POST':
48             do_something_else()
50 .. attribute:: HttpRequest.encoding
52     **New in Django development version**
54     A string representing the current encoding used to decode form submission
55     data (or ``None``, which means the ``DEFAULT_CHARSET`` setting is used).
56     You can write to this attribute to change the encoding used when accessing
57     the form data. Any subsequent attribute accesses (such as reading from
58     ``GET`` or ``POST``) will use the new ``encoding`` value.  Useful if you
59     know the form data is not in the ``DEFAULT_CHARSET`` encoding.
61 .. attribute:: HttpRequest.GET
63     A dictionary-like object containing all given HTTP GET parameters. See the
64     ``QueryDict`` documentation below.
66 .. attribute:: HttpRequest.POST
68     A dictionary-like object containing all given HTTP POST parameters. See the
69     ``QueryDict`` documentation below.
71     It's possible that a request can come in via POST with an empty ``POST``
72     dictionary -- if, say, a form is requested via the POST HTTP method but
73     does not include form data. Therefore, you shouldn't use ``if request.POST``
74     to check for use of the POST method; instead, use ``if request.method ==
75     "POST"`` (see above).
77     Note: ``POST`` does *not* include file-upload information. See ``FILES``.
79 .. attribute:: HttpRequest.REQUEST
81     For convenience, a dictionary-like object that searches ``POST`` first,
82     then ``GET``. Inspired by PHP's ``$_REQUEST``.
84     For example, if ``GET = {"name": "john"}`` and ``POST = {"age": '34'}``,
85     ``REQUEST["name"]`` would be ``"john"``, and ``REQUEST["age"]`` would be
86     ``"34"``.
88     It's strongly suggested that you use ``GET`` and ``POST`` instead of
89     ``REQUEST``, because the former are more explicit.
91 .. attribute:: HttpRequest.COOKIES
93     A standard Python dictionary containing all cookies. Keys and values are
94     strings.
96 .. attribute:: HttpRequest.FILES 
98     .. admonition:: Changed in Django development version
99         
100         In previous versions of Django, ``request.FILES`` contained
101         simple ``dict`` objects representing uploaded files. This is
102         no longer true -- files are represented by ``UploadedFile``
103         objects as described below.
104         
105         These ``UploadedFile`` objects will emulate the old-style ``dict``
106         interface, but this is deprecated and will be removed in the next
107         release of Django.
109     A dictionary-like object containing all uploaded files. Each key in
110     ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each
111     value in ``FILES`` is an ``UploadedFile`` object containing the following
112     attributes:
114         * ``read(num_bytes=None)`` -- Read a number of bytes from the file.
115         * ``name`` -- The name of the uploaded file.
116         * ``size`` -- The size, in bytes, of the uploaded file.
117         * ``chunks(chunk_size=None)`` -- A generator that yields sequential chunks of data.
119     See :ref:`topics-files` for more information.
121     Note that ``FILES`` will only contain data if the request method was POST
122     and the ``<form>`` that posted to the request had
123     ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank
124     dictionary-like object.
126 .. attribute:: HttpRequest.META
128     A standard Python dictionary containing all available HTTP headers.
129     Available headers depend on the client and server, but here are some
130     examples:
132         * ``CONTENT_LENGTH``
133         * ``CONTENT_TYPE``
134         * ``HTTP_ACCEPT_ENCODING``
135         * ``HTTP_ACCEPT_LANGUAGE``
136         * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
137         * ``HTTP_REFERER`` -- The referring page, if any.
138         * ``HTTP_USER_AGENT`` -- The client's user-agent string.
139         * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
140         * ``REMOTE_ADDR`` -- The IP address of the client.
141         * ``REMOTE_HOST`` -- The hostname of the client.
142         * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
143         * ``SERVER_NAME`` -- The hostname of the server.
144         * ``SERVER_PORT`` -- The port of the server.
146 .. attribute:: HttpRequest.user
148     A ``django.contrib.auth.models.User`` object representing the currently
149     logged-in user. If the user isn't currently logged in, ``user`` will be set
150     to an instance of ``django.contrib.auth.models.AnonymousUser``. You
151     can tell them apart with ``is_authenticated()``, like so::
153         if request.user.is_authenticated():
154             # Do something for logged-in users.
155         else:
156             # Do something for anonymous users.
158     ``user`` is only available if your Django installation has the
159     ``AuthenticationMiddleware`` activated. For more, see
160     :ref:`topics-auth`.
162 .. attribute:: HttpRequest.session
164     A readable-and-writable, dictionary-like object that represents the current
165     session. This is only available if your Django installation has session
166     support activated. See the :ref:`session documentation
167     <topics-http-sessions>` for full details.
169 .. attribute:: HttpRequest.raw_post_data
171     The raw HTTP POST data. This is only useful for advanced processing. Use
172     ``POST`` instead.
174 .. attribute:: HttpRequest.urlconf
176     Not defined by Django itself, but will be read if other code (e.g., a custom
177     middleware class) sets it. When present, this will be used as the root
178     URLconf for the current request, overriding the ``ROOT_URLCONF`` setting.
179     See :ref:`how-django-processes-a-request` for details.
181 Methods
182 -------
184 .. method:: HttpRequest.get_host()
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"``
197 .. method:: HttpRequest.get_full_path()
199    Returns the ``path``, plus an appended query string, if applicable.
201    Example: ``"/music/bands/the_beatles/?print=true"``
203 .. method:: HttpRequest.build_absolute_uri(location)
205    **New in Django development version**
207    Returns the absolute URI form of ``location``. If no location is provided,
208    the location will be set to ``request.get_full_path()``.
210    If the location is already an absolute URI, it will not be altered.
211    Otherwise the absolute URI is built using the server variables available in
212    this request.
214    Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
216 .. method:: HttpRequest.is_secure()
218    Returns ``True`` if the request is secure; that is, if it was made with
219    HTTPS.
221 .. method:: HttpRequest.is_ajax()
223    **New in Django development version**
225    Returns ``True`` if the request was made via an ``XMLHttpRequest``, by checking
226    the ``HTTP_X_REQUESTED_WITH`` header for the string ``'XMLHttpRequest'``. The
227    following major JavaScript libraries all send this header:
229        * jQuery
230        * Dojo
231        * MochiKit
232        * MooTools
233        * Prototype
234        * YUI
236    If you write your own XMLHttpRequest call (on the browser side), you'll
237    have to set this header manually if you want ``is_ajax()`` to work.
240 QueryDict objects
241 -----------------
243 .. class:: QueryDict
245 In an :class:`HttpRequest` object, the ``GET`` and ``POST`` attributes are instances
246 of ``django.http.QueryDict``. :class:`QueryDict` is a dictionary-like
247 class customized to deal with multiple values for the same key. This is
248 necessary because some HTML form elements, notably
249 ``<select multiple="multiple">``, pass multiple values for the same key.
251 ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
252 That means you can't change attributes of ``request.POST`` and ``request.GET``
253 directly.
255 Methods
256 -------
258 :class:`QueryDict` implements all the standard dictionary methods, because it's
259 a subclass of dictionary. Exceptions are outlined here:
261 .. method:: QueryDict.__getitem__(key)
263     Returns the value for the given key. If the key has more than one value,
264     ``__getitem__()`` returns the last value. Raises
265     ``django.utils.datastructure.MultiValueDictKeyError`` if the key does not
266     exist. (This is a subclass of Python's standard ``KeyError``, so you can
267     stick to catching ``KeyError``.)
269 .. method:: QueryDict.__setitem__(key, value)
271     Sets the given key to ``[value]`` (a Python list whose single element is
272     ``value``). Note that this, as other dictionary functions that have side
273     effects, can only be called on a mutable ``QueryDict`` (one that was created
274     via ``copy()``).
276 .. method:: QueryDict.__contains__(key)
278     Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
279     in request.GET``.
281 .. method:: QueryDict.get(key, default)
283     Uses the same logic as ``__getitem__()`` above, with a hook for returning a
284     default value if the key doesn't exist.
286 .. method:: QueryDict.setdefault(key, default)
288     Just like the standard dictionary ``setdefault()`` method, except it uses
289     ``__setitem__`` internally.
291 .. method:: QueryDict.update(other_dict) 
293     Takes either a ``QueryDict`` or standard dictionary. Just like the standard
294     dictionary ``update()`` method, except it *appends* to the current
295     dictionary items rather than replacing them. For example::
297           >>> q = QueryDict('a=1')
298           >>> q = q.copy() # to make it mutable
299           >>> q.update({'a': '2'})
300           >>> q.getlist('a')
301           ['1', '2']
302           >>> q['a'] # returns the last
303           ['2']
305 .. method:: QueryDict.items()
307     Just like the standard dictionary ``items()`` method, except this uses the
308     same last-value logic as ``__getitem()__``. For example::
310            >>> q = QueryDict('a=1&a=2&a=3')
311            >>> q.items()
312            [('a', '3')]
314 .. method:: QueryDict.values()
316     Just like the standard dictionary ``values()`` method, except this uses the
317     same last-value logic as ``__getitem()__``. For example::
319            >>> q = QueryDict('a=1&a=2&a=3')
320            >>> q.values()
321            ['3']
323 In addition, ``QueryDict`` has the following methods:
325 .. method:: QueryDict.copy()
327     Returns a copy of the object, using ``copy.deepcopy()`` from the Python
328     standard library. The copy will be mutable -- that is, you can change its
329     values.
331 .. method:: QueryDict.getlist(key)
333     Returns the data with the requested key, as a Python list. Returns an
334     empty list if the key doesn't exist. It's guaranteed to return a list of
335     some sort.
337 .. method:: QueryDict.setlist(key, list_)
339     Sets the given key to ``list_`` (unlike ``__setitem__()``).
341 .. method:: QueryDict.appendlist(key, item)
343     Appends an item to the internal list associated with key.
345 .. method:: QueryDict.setlistdefault(key, default_list)
347     Just like ``setdefault``, except it takes a list of values instead of a
348     single value.
350 .. method:: QueryDict.lists()
352     Like :method:items(), except it includes all values, as a list, for each
353     member of the dictionary. For example::
354     
355          >>> q = QueryDict('a=1&a=2&a=3')
356          >>> q.lists()
357          [('a', ['1', '2', '3'])]
358     
359 .. method:: QueryDict.urlencode()
361     Returns a string of the data in query-string format.
362     Example: ``"a=2&b=3&b=5"``.
364 HttpResponse objects
365 ====================
367 .. class:: HttpResponse
369 In contrast to :class:`HttpRequest` objects, which are created automatically by
370 Django, :class:`HttpResponse` objects are your responsibility. Each view you
371 write is responsible for instantiating, populating and returning an
372 :class:`HttpResponse`.
374 The :class:`HttpResponse` class lives in the ``django.http`` module.
376 Usage
377 -----
379 Passing strings
380 ~~~~~~~~~~~~~~~
382 Typical usage is to pass the contents of the page, as a string, to the
383 :class:`HttpResponse` constructor::
385     >>> response = HttpResponse("Here's the text of the Web page.")
386     >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
388 But if you want to add content incrementally, you can use ``response`` as a
389 file-like object::
391     >>> response = HttpResponse()
392     >>> response.write("<p>Here's the text of the Web page.</p>")
393     >>> response.write("<p>Here's another paragraph.</p>")
395 You can add and delete headers using dictionary syntax::
397     >>> response = HttpResponse()
398     >>> response['X-DJANGO'] = "It's the best."
399     >>> del response['X-PHP']
400     >>> response['X-DJANGO']
401     "It's the best."
403 Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist.
405 Passing iterators
406 ~~~~~~~~~~~~~~~~~
408 Finally, you can pass ``HttpResponse`` an iterator rather than passing it
409 hard-coded strings. If you use this technique, follow these guidelines:
411     * The iterator should return strings.
412     * If an :class:`HttpResponse` has been initialized with an iterator as its
413       content, you can't use the class:`HttpResponse` instance as a file-like
414       object. Doing so will raise ``Exception``.
416 Setting headers
417 ~~~~~~~~~~~~~~~
419 To set a header in your response, just treat it like a dictionary::
421     >>> response = HttpResponse()
422     >>> response['Pragma'] = 'no-cache'
424 Telling the browser to treat the response as a file attachment
425 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
427 To tell the browser to treat the response as a file attachment, use the
428 ``mimetype`` argument and set the ``Content-Disposition`` header. For example,
429 this is how you might return a Microsoft Excel spreadsheet::
431     >>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
432     >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
434 There's nothing Django-specific about the ``Content-Disposition`` header, but
435 it's easy to forget the syntax, so we've included it here.
437 Methods
438 -------
440 .. method:: HttpResponse.__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE)
441     
442     Instantiates an ``HttpResponse`` object with the given page content (a
443     string) and MIME type. The ``DEFAULT_CONTENT_TYPE`` is ``'text/html'``.
445     ``content`` can be an iterator or a string. If it's an iterator, it should
446     return strings, and those strings will be joined together to form the
447     content of the response.
449     ``status`` is the `HTTP Status code`_ for the response.
451     **(New in Django development version)** ``content_type`` is an alias for
452     ``mimetype``. Historically, the parameter was only called ``mimetype``,
453     but since this is actually the value included in the HTTP ``Content-Type``
454     header, it can also include the character set encoding, which makes it
455     more than just a MIME type specification. If ``mimetype`` is specified
456     (not ``None``), that value is used. Otherwise, ``content_type`` is used. If
457     neither is given, the ``DEFAULT_CONTENT_TYPE`` setting is used.
459 .. method:: HttpResponse.__setitem__(header, value)
461     Sets the given header name to the given value. Both ``header`` and
462     ``value`` should be strings.
464 .. method:: HttpResponse.__delitem__(header)
466     Deletes the header with the given name. Fails silently if the header
467     doesn't exist. Case-sensitive.
469 .. method:: HttpResponse.__getitem__(header)
471     Returns the value for the given header name. Case-sensitive.
473 .. method:: HttpResponse.has_header(header)
475     Returns ``True`` or ``False`` based on a case-insensitive check for a
476     header with the given name.
478 .. method:: HttpResponse.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 .. method:: HttpResponse.delete_cookie(key, path='/', domain=None)
497     Deletes the cookie with the given key. Fails silently if the key doesn't
498     exist.
500     Due to the way cookies work, ``path`` and ``domain`` should be the same
501     values you used in ``set_cookie()`` -- otherwise the cookie may not be
502     deleted.
504 .. method:: HttpResponse.content()
506     Returns the content as a Python string, encoding it from a Unicode object
507     if necessary. Note this is a property, not a method, so use ``r.content``
508     instead of ``r.content()``.
510 .. method:: HttpResponse.write(content)
512     This method makes an :class:`HttpResponse` instance a file-like object.
514 .. method:: HttpResponse.flush()
516     This method makes an :class:`HttpResponse` instance a file-like object.
518 .. method:: HttpResponse.tell()
520     This method makes an :class:`HttpResponse` instance a file-like object.
522 .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
525 HttpResponse subclasses
526 -----------------------
528 Django includes a number of ``HttpResponse`` subclasses that handle different
529 types of HTTP responses. Like ``HttpResponse``, these subclasses live in
530 :mod:`django.http`.
532 .. class:: HttpResponseRedirect
534     The constructor takes a single argument -- the path to redirect to. This
535     can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or an
536     absolute URL with no domain (e.g. ``'/search/'``). Note that this returns
537     an HTTP status code 302.
539 .. class:: HttpResponsePermanentRedirect
541     Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
542     (HTTP status code 301) instead of a "found" redirect (status code 302).
544 .. class:: HttpResponseNotModified
546     The constructor doesn't take any arguments. Use this to designate that a
547     page hasn't been modified since the user's last request (status code 304).
549 .. class:: HttpResponseBadRequest
551     **New in Django development version.** Acts just like :class:`HttpResponse`
552     but uses a 400 status code.
554 .. class:: HttpResponseNotFound
556     Acts just like :class:`HttpResponse` but uses a 404 status code.
558 .. class:: HttpResponseForbidden
560     Acts just like :class:`HttpResponse` but uses a 403 status code.
562 .. class:: HttpResponseNotAllowed
564     Like :class:`HttpResponse`, but uses a 405 status code. Takes a single,
565     required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
567 .. class:: HttpResponseGone
569     Acts just like :class:`HttpResponse` but uses a 410 status code.
571 .. class:: HttpResponseServerError
573     Acts just like :class:`HttpResponse` but uses a 500 status code.