Fixed #9199 -- We were erroneously only prepending "www" to the domain if we
[django.git] / docs / ref / request-response.txt
blobd8f4fe04a091d15a8490ba166c3aa67dc19e9bad
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     .. versionadded:: 1.0
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     A dictionary-like object containing all uploaded files. Each key in
99     ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each
100     value in ``FILES`` is an ``UploadedFile`` object containing the following
101     attributes:
103         * ``read(num_bytes=None)`` -- Read a number of bytes from the file.
104         * ``name`` -- The name of the uploaded file.
105         * ``size`` -- The size, in bytes, of the uploaded file.
106         * ``chunks(chunk_size=None)`` -- A generator that yields sequential chunks of data.
108     See :ref:`topics-files` for more information.
110     Note that ``FILES`` will only contain data if the request method was POST
111     and the ``<form>`` that posted to the request had
112     ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank
113     dictionary-like object.
115     .. versionchanged:: 1.0
117     In previous versions of Django, ``request.FILES`` contained simple ``dict``
118     objects representing uploaded files. This is no longer true -- files are
119     represented by ``UploadedFile`` objects as described below.
121     These ``UploadedFile`` objects will emulate the old-style ``dict``
122     interface, but this is deprecated and will be removed in the next release of
123     Django.
125 .. attribute:: HttpRequest.META
127     A standard Python dictionary containing all available HTTP headers.
128     Available headers depend on the client and server, but here are some
129     examples:
131         * ``CONTENT_LENGTH``
132         * ``CONTENT_TYPE``
133         * ``HTTP_ACCEPT_ENCODING``
134         * ``HTTP_ACCEPT_LANGUAGE``
135         * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
136         * ``HTTP_REFERER`` -- The referring page, if any.
137         * ``HTTP_USER_AGENT`` -- The client's user-agent string.
138         * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
139         * ``REMOTE_ADDR`` -- The IP address of the client.
140         * ``REMOTE_HOST`` -- The hostname of the client.
141         * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
142         * ``SERVER_NAME`` -- The hostname of the server.
143         * ``SERVER_PORT`` -- The port of the server.
145 .. attribute:: HttpRequest.user
147     A ``django.contrib.auth.models.User`` object representing the currently
148     logged-in user. If the user isn't currently logged in, ``user`` will be set
149     to an instance of ``django.contrib.auth.models.AnonymousUser``. You
150     can tell them apart with ``is_authenticated()``, like so::
152         if request.user.is_authenticated():
153             # Do something for logged-in users.
154         else:
155             # Do something for anonymous users.
157     ``user`` is only available if your Django installation has the
158     ``AuthenticationMiddleware`` activated. For more, see
159     :ref:`topics-auth`.
161 .. attribute:: HttpRequest.session
163     A readable-and-writable, dictionary-like object that represents the current
164     session. This is only available if your Django installation has session
165     support activated. See the :ref:`session documentation
166     <topics-http-sessions>` for full details.
168 .. attribute:: HttpRequest.raw_post_data
170     The raw HTTP POST data. This is only useful for advanced processing. Use
171     ``POST`` instead.
173 .. attribute:: HttpRequest.urlconf
175     Not defined by Django itself, but will be read if other code (e.g., a custom
176     middleware class) sets it. When present, this will be used as the root
177     URLconf for the current request, overriding the ``ROOT_URLCONF`` setting.
178     See :ref:`how-django-processes-a-request` for details.
180 Methods
181 -------
183 .. method:: HttpRequest.get_host()
185    .. versionadded:: 1.0
187    Returns the originating host of the request using information from the
188    ``HTTP_X_FORWARDED_HOST`` and ``HTTP_HOST`` headers (in that order). If
189    they don't provide a value, the method uses a combination of
190    ``SERVER_NAME`` and ``SERVER_PORT`` as detailed in `PEP 333`_.
192    .. _PEP 333: http://www.python.org/dev/peps/pep-0333/
194    Example: ``"127.0.0.1:8000"``
196 .. method:: HttpRequest.get_full_path()
198    Returns the ``path``, plus an appended query string, if applicable.
200    Example: ``"/music/bands/the_beatles/?print=true"``
202 .. method:: HttpRequest.build_absolute_uri(location)
204    .. versionadded:: 1.0
206    Returns the absolute URI form of ``location``. If no location is provided,
207    the location will be set to ``request.get_full_path()``.
209    If the location is already an absolute URI, it will not be altered.
210    Otherwise the absolute URI is built using the server variables available in
211    this request.
213    Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
215 .. method:: HttpRequest.is_secure()
217    Returns ``True`` if the request is secure; that is, if it was made with
218    HTTPS.
220 .. method:: HttpRequest.is_ajax()
222    .. versionadded:: 1.0
224    Returns ``True`` if the request was made via an ``XMLHttpRequest``, by checking
225    the ``HTTP_X_REQUESTED_WITH`` header for the string ``'XMLHttpRequest'``. The
226    following major JavaScript libraries all send this header:
228        * jQuery
229        * Dojo
230        * MochiKit
231        * MooTools
232        * Prototype
233        * YUI
235    If you write your own XMLHttpRequest call (on the browser side), you'll
236    have to set this header manually if you want ``is_ajax()`` to work.
239 QueryDict objects
240 -----------------
242 .. class:: QueryDict
244 In an :class:`HttpRequest` object, the ``GET`` and ``POST`` attributes are instances
245 of ``django.http.QueryDict``. :class:`QueryDict` is a dictionary-like
246 class customized to deal with multiple values for the same key. This is
247 necessary because some HTML form elements, notably
248 ``<select multiple="multiple">``, pass multiple values for the same key.
250 ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
251 That means you can't change attributes of ``request.POST`` and ``request.GET``
252 directly.
254 Methods
255 -------
257 :class:`QueryDict` implements all the standard dictionary methods, because it's
258 a subclass of dictionary. Exceptions are outlined here:
260 .. method:: QueryDict.__getitem__(key)
262     Returns the value for the given key. If the key has more than one value,
263     ``__getitem__()`` returns the last value. Raises
264     ``django.utils.datastructure.MultiValueDictKeyError`` if the key does not
265     exist. (This is a subclass of Python's standard ``KeyError``, so you can
266     stick to catching ``KeyError``.)
268 .. method:: QueryDict.__setitem__(key, value)
270     Sets the given key to ``[value]`` (a Python list whose single element is
271     ``value``). Note that this, as other dictionary functions that have side
272     effects, can only be called on a mutable ``QueryDict`` (one that was created
273     via ``copy()``).
275 .. method:: QueryDict.__contains__(key)
277     Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
278     in request.GET``.
280 .. method:: QueryDict.get(key, default)
282     Uses the same logic as ``__getitem__()`` above, with a hook for returning a
283     default value if the key doesn't exist.
285 .. method:: QueryDict.setdefault(key, default)
287     Just like the standard dictionary ``setdefault()`` method, except it uses
288     ``__setitem__`` internally.
290 .. method:: QueryDict.update(other_dict) 
292     Takes either a ``QueryDict`` or standard dictionary. Just like the standard
293     dictionary ``update()`` method, except it *appends* to the current
294     dictionary items rather than replacing them. For example::
296           >>> q = QueryDict('a=1')
297           >>> q = q.copy() # to make it mutable
298           >>> q.update({'a': '2'})
299           >>> q.getlist('a')
300           ['1', '2']
301           >>> q['a'] # returns the last
302           ['2']
304 .. method:: QueryDict.items()
306     Just like the standard dictionary ``items()`` method, except this uses the
307     same last-value logic as ``__getitem()__``. For example::
309            >>> q = QueryDict('a=1&a=2&a=3')
310            >>> q.items()
311            [('a', '3')]
313 .. method:: QueryDict.values()
315     Just like the standard dictionary ``values()`` method, except this uses the
316     same last-value logic as ``__getitem()__``. For example::
318            >>> q = QueryDict('a=1&a=2&a=3')
319            >>> q.values()
320            ['3']
322 In addition, ``QueryDict`` has the following methods:
324 .. method:: QueryDict.copy()
326     Returns a copy of the object, using ``copy.deepcopy()`` from the Python
327     standard library. The copy will be mutable -- that is, you can change its
328     values.
330 .. method:: QueryDict.getlist(key)
332     Returns the data with the requested key, as a Python list. Returns an
333     empty list if the key doesn't exist. It's guaranteed to return a list of
334     some sort.
336 .. method:: QueryDict.setlist(key, list_)
338     Sets the given key to ``list_`` (unlike ``__setitem__()``).
340 .. method:: QueryDict.appendlist(key, item)
342     Appends an item to the internal list associated with key.
344 .. method:: QueryDict.setlistdefault(key, default_list)
346     Just like ``setdefault``, except it takes a list of values instead of a
347     single value.
349 .. method:: QueryDict.lists()
351     Like :meth:`items()`, except it includes all values, as a list, for each
352     member of the dictionary. For example::
353     
354          >>> q = QueryDict('a=1&a=2&a=3')
355          >>> q.lists()
356          [('a', ['1', '2', '3'])]
357     
358 .. method:: QueryDict.urlencode()
360     Returns a string of the data in query-string format.
361     Example: ``"a=2&b=3&b=5"``.
363 HttpResponse objects
364 ====================
366 .. class:: HttpResponse
368 In contrast to :class:`HttpRequest` objects, which are created automatically by
369 Django, :class:`HttpResponse` objects are your responsibility. Each view you
370 write is responsible for instantiating, populating and returning an
371 :class:`HttpResponse`.
373 The :class:`HttpResponse` class lives in the ``django.http`` module.
375 Usage
376 -----
378 Passing strings
379 ~~~~~~~~~~~~~~~
381 Typical usage is to pass the contents of the page, as a string, to the
382 :class:`HttpResponse` constructor::
384     >>> response = HttpResponse("Here's the text of the Web page.")
385     >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
387 But if you want to add content incrementally, you can use ``response`` as a
388 file-like object::
390     >>> response = HttpResponse()
391     >>> response.write("<p>Here's the text of the Web page.</p>")
392     >>> response.write("<p>Here's another paragraph.</p>")
394 You can add and delete headers using dictionary syntax::
396     >>> response = HttpResponse()
397     >>> response['X-DJANGO'] = "It's the best."
398     >>> del response['X-PHP']
399     >>> response['X-DJANGO']
400     "It's the best."
402 Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist.
404 Passing iterators
405 ~~~~~~~~~~~~~~~~~
407 Finally, you can pass ``HttpResponse`` an iterator rather than passing it
408 hard-coded strings. If you use this technique, follow these guidelines:
410     * The iterator should return strings.
411     * If an :class:`HttpResponse` has been initialized with an iterator as its
412       content, you can't use the class:`HttpResponse` instance as a file-like
413       object. Doing so will raise ``Exception``.
415 Setting headers
416 ~~~~~~~~~~~~~~~
418 To set a header in your response, just treat it like a dictionary::
420     >>> response = HttpResponse()
421     >>> response['Pragma'] = 'no-cache'
423 Telling the browser to treat the response as a file attachment
424 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
426 To tell the browser to treat the response as a file attachment, use the
427 ``mimetype`` argument and set the ``Content-Disposition`` header. For example,
428 this is how you might return a Microsoft Excel spreadsheet::
430     >>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
431     >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
433 There's nothing Django-specific about the ``Content-Disposition`` header, but
434 it's easy to forget the syntax, so we've included it here.
436 Attributes
437 ----------
439 .. attribute:: HttpResponse.content
441     A normal Python string representing the content, encoded from a Unicode
442     object if necessary.
444 Methods
445 -------
447 .. method:: HttpResponse.__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE)
448     
449     Instantiates an ``HttpResponse`` object with the given page content (a
450     string) and MIME type. The ``DEFAULT_CONTENT_TYPE`` is ``'text/html'``.
452     ``content`` can be an iterator or a string. If it's an iterator, it should
453     return strings, and those strings will be joined together to form the
454     content of the response.
456     ``status`` is the `HTTP Status code`_ for the response.
458     .. versionadded:: 1.0
460     ``content_type`` is an alias for ``mimetype``. Historically, this parameter
461     was only called ``mimetype``, but since this is actually the value included
462     in the HTTP ``Content-Type`` header, it can also include the character set
463     encoding, which makes it more than just a MIME type specification.
464     If ``mimetype`` is specified (not ``None``), that value is used.
465     Otherwise, ``content_type`` is used. If neither is given, the
466     ``DEFAULT_CONTENT_TYPE`` setting is used.
468 .. method:: HttpResponse.__setitem__(header, value)
470     Sets the given header name to the given value. Both ``header`` and
471     ``value`` should be strings.
473 .. method:: HttpResponse.__delitem__(header)
475     Deletes the header with the given name. Fails silently if the header
476     doesn't exist. Case-sensitive.
478 .. method:: HttpResponse.__getitem__(header)
480     Returns the value for the given header name. Case-sensitive.
482 .. method:: HttpResponse.has_header(header)
484     Returns ``True`` or ``False`` based on a case-insensitive check for a
485     header with the given name.
487 .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)
489     Sets a cookie. The parameters are the same as in the `cookie Morsel`_
490     object in the Python standard library.
492         * ``max_age`` should be a number of seconds, or ``None`` (default) if
493           the cookie should last only as long as the client's browser session.
494         * ``expires`` should be a string in the format
495           ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``.
496         * Use ``domain`` if you want to set a cross-domain cookie. For example,
497           ``domain=".lawrence.com"`` will set a cookie that is readable by
498           the domains www.lawrence.com, blogs.lawrence.com and
499           calendars.lawrence.com. Otherwise, a cookie will only be readable by
500           the domain that set it.
502     .. _`cookie Morsel`: http://www.python.org/doc/current/lib/morsel-objects.html
504 .. method:: HttpResponse.delete_cookie(key, path='/', domain=None)
506     Deletes the cookie with the given key. Fails silently if the key doesn't
507     exist.
509     Due to the way cookies work, ``path`` and ``domain`` should be the same
510     values you used in ``set_cookie()`` -- otherwise the cookie may not be
511     deleted.
513 .. method:: HttpResponse.write(content)
515     This method makes an :class:`HttpResponse` instance a file-like object.
517 .. method:: HttpResponse.flush()
519     This method makes an :class:`HttpResponse` instance a file-like object.
521 .. method:: HttpResponse.tell()
523     This method makes an :class:`HttpResponse` instance a file-like object.
525 .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
528 HttpResponse subclasses
529 -----------------------
531 Django includes a number of ``HttpResponse`` subclasses that handle different
532 types of HTTP responses. Like ``HttpResponse``, these subclasses live in
533 :mod:`django.http`.
535 .. class:: HttpResponseRedirect
537     The constructor takes a single argument -- the path to redirect to. This
538     can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or an
539     absolute URL with no domain (e.g. ``'/search/'``). Note that this returns
540     an HTTP status code 302.
542 .. class:: HttpResponsePermanentRedirect
544     Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
545     (HTTP status code 301) instead of a "found" redirect (status code 302).
547 .. class:: HttpResponseNotModified
549     The constructor doesn't take any arguments. Use this to designate that a
550     page hasn't been modified since the user's last request (status code 304).
552 .. class:: HttpResponseBadRequest
554     .. versionadded:: 1.0
556     Acts just like :class:`HttpResponse` but uses a 400 status code.
558 .. class:: HttpResponseNotFound
560     Acts just like :class:`HttpResponse` but uses a 404 status code.
562 .. class:: HttpResponseForbidden
564     Acts just like :class:`HttpResponse` but uses a 403 status code.
566 .. class:: HttpResponseNotAllowed
568     Like :class:`HttpResponse`, but uses a 405 status code. Takes a single,
569     required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
571 .. class:: HttpResponseGone
573     Acts just like :class:`HttpResponse` but uses a 410 status code.
575 .. class:: HttpResponseServerError
577     Acts just like :class:`HttpResponse` but uses a 500 status code.