request-response.txt 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. ============================
  2. Request and response objects
  3. ============================
  4. .. module:: django.http
  5. :synopsis: Classes dealing with HTTP requests and responses.
  6. Quick overview
  7. ==============
  8. Django uses request and response objects to pass state through the system.
  9. When a page is requested, Django creates an :class:`HttpRequest` object that
  10. contains metadata about the request. Then Django loads the appropriate view,
  11. passing the :class:`HttpRequest` as the first argument to the view function.
  12. Each view is responsible for returning an :class:`HttpResponse` object.
  13. This document explains the APIs for :class:`HttpRequest` and
  14. :class:`HttpResponse` objects.
  15. HttpRequest objects
  16. ===================
  17. .. class:: HttpRequest
  18. Attributes
  19. ----------
  20. All attributes except ``session`` should be considered read-only.
  21. .. attribute:: HttpRequest.path
  22. A string representing the full path to the requested page, not including
  23. the domain.
  24. Example: ``"/music/bands/the_beatles/"``
  25. .. attribute:: HttpRequest.path_info
  26. Under some Web server configurations, the portion of the URL after the host
  27. name is split up into a script prefix portion and a path info portion
  28. (this happens, for example, when using the ``django.root`` option
  29. with the :doc:`modpython handler from Apache </howto/deployment/modpython>`).
  30. The ``path_info`` attribute always contains the path info portion of the
  31. path, no matter what Web server is being used. Using this instead of
  32. attr:`~HttpRequest.path` can make your code much easier to move between test
  33. and deployment servers.
  34. For example, if the ``django.root`` for your application is set to
  35. ``"/minfo"``, then ``path`` might be ``"/minfo/music/bands/the_beatles/"``
  36. and ``path_info`` would be ``"/music/bands/the_beatles/"``.
  37. .. attribute:: HttpRequest.method
  38. A string representing the HTTP method used in the request. This is
  39. guaranteed to be uppercase. Example::
  40. if request.method == 'GET':
  41. do_something()
  42. elif request.method == 'POST':
  43. do_something_else()
  44. .. attribute:: HttpRequest.encoding
  45. A string representing the current encoding used to decode form submission
  46. data (or ``None``, which means the :setting:`DEFAULT_CHARSET` setting is
  47. used). You can write to this attribute to change the encoding used when
  48. accessing the form data. Any subsequent attribute accesses (such as reading
  49. from ``GET`` or ``POST``) will use the new ``encoding`` value. Useful if
  50. you know the form data is not in the :setting:`DEFAULT_CHARSET` encoding.
  51. .. attribute:: HttpRequest.GET
  52. A dictionary-like object containing all given HTTP GET parameters. See the
  53. :class:`QueryDict` documentation below.
  54. .. attribute:: HttpRequest.POST
  55. A dictionary-like object containing all given HTTP POST parameters. See the
  56. :class:`QueryDict` documentation below.
  57. It's possible that a request can come in via POST with an empty ``POST``
  58. dictionary -- if, say, a form is requested via the POST HTTP method but
  59. does not include form data. Therefore, you shouldn't use ``if request.POST``
  60. to check for use of the POST method; instead, use ``if request.method ==
  61. "POST"`` (see above).
  62. Note: ``POST`` does *not* include file-upload information. See ``FILES``.
  63. .. attribute:: HttpRequest.REQUEST
  64. For convenience, a dictionary-like object that searches ``POST`` first,
  65. then ``GET``. Inspired by PHP's ``$_REQUEST``.
  66. For example, if ``GET = {"name": "john"}`` and ``POST = {"age": '34'}``,
  67. ``REQUEST["name"]`` would be ``"john"``, and ``REQUEST["age"]`` would be
  68. ``"34"``.
  69. It's strongly suggested that you use ``GET`` and ``POST`` instead of
  70. ``REQUEST``, because the former are more explicit.
  71. .. attribute:: HttpRequest.COOKIES
  72. A standard Python dictionary containing all cookies. Keys and values are
  73. strings.
  74. .. attribute:: HttpRequest.FILES
  75. A dictionary-like object containing all uploaded files. Each key in
  76. ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each
  77. value in ``FILES`` is an :class:`UploadedFile` as described below.
  78. See :doc:`/topics/files` for more information.
  79. Note that ``FILES`` will only contain data if the request method was POST
  80. and the ``<form>`` that posted to the request had
  81. ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank
  82. dictionary-like object.
  83. .. attribute:: HttpRequest.META
  84. A standard Python dictionary containing all available HTTP headers.
  85. Available headers depend on the client and server, but here are some
  86. examples:
  87. * ``CONTENT_LENGTH``
  88. * ``CONTENT_TYPE``
  89. * ``HTTP_ACCEPT_ENCODING``
  90. * ``HTTP_ACCEPT_LANGUAGE``
  91. * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
  92. * ``HTTP_REFERER`` -- The referring page, if any.
  93. * ``HTTP_USER_AGENT`` -- The client's user-agent string.
  94. * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
  95. * ``REMOTE_ADDR`` -- The IP address of the client.
  96. * ``REMOTE_HOST`` -- The hostname of the client.
  97. * ``REMOTE_USER`` -- The user authenticated by the Web server, if any.
  98. * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
  99. * ``SERVER_NAME`` -- The hostname of the server.
  100. * ``SERVER_PORT`` -- The port of the server.
  101. With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given
  102. above, any HTTP headers in the request are converted to ``META`` keys by
  103. converting all characters to uppercase, replacing any hyphens with
  104. underscores and adding an ``HTTP_`` prefix to the name. So, for example, a
  105. header called ``X-Bender`` would be mapped to the ``META`` key
  106. ``HTTP_X_BENDER``.
  107. .. attribute:: HttpRequest.user
  108. A ``django.contrib.auth.models.User`` object representing the currently
  109. logged-in user. If the user isn't currently logged in, ``user`` will be set
  110. to an instance of ``django.contrib.auth.models.AnonymousUser``. You
  111. can tell them apart with ``is_authenticated()``, like so::
  112. if request.user.is_authenticated():
  113. # Do something for logged-in users.
  114. else:
  115. # Do something for anonymous users.
  116. ``user`` is only available if your Django installation has the
  117. ``AuthenticationMiddleware`` activated. For more, see
  118. :doc:`/topics/auth`.
  119. .. attribute:: HttpRequest.session
  120. A readable-and-writable, dictionary-like object that represents the current
  121. session. This is only available if your Django installation has session
  122. support activated. See the :doc:`session documentation
  123. </topics/http/sessions>` for full details.
  124. .. attribute:: HttpRequest.raw_post_data
  125. The raw HTTP POST data as a byte string. This is useful for processing
  126. data in different formats than of conventional HTML forms: binary images,
  127. XML payload etc. For processing form data use ``HttpRequest.POST``.
  128. .. versionadded:: 1.3
  129. You can also read from an HttpRequest using file-like interface. See
  130. :meth:`HttpRequest.read()`.
  131. .. attribute:: HttpRequest.urlconf
  132. Not defined by Django itself, but will be read if other code (e.g., a custom
  133. middleware class) sets it. When present, this will be used as the root
  134. URLconf for the current request, overriding the :setting:`ROOT_URLCONF`
  135. setting. See :ref:`how-django-processes-a-request` for details.
  136. Methods
  137. -------
  138. .. method:: HttpRequest.get_host()
  139. Returns the originating host of the request using information from the
  140. ``HTTP_X_FORWARDED_HOST`` and ``HTTP_HOST`` headers (in that order). If
  141. they don't provide a value, the method uses a combination of
  142. ``SERVER_NAME`` and ``SERVER_PORT`` as detailed in `PEP 333`_.
  143. .. _PEP 333: http://www.python.org/dev/peps/pep-0333/
  144. Example: ``"127.0.0.1:8000"``
  145. .. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is
  146. behind multiple proxies. One solution is to use middleware to rewrite
  147. the proxy headers, as in the following example::
  148. class MultipleProxyMiddleware(object):
  149. FORWARDED_FOR_FIELDS = [
  150. 'HTTP_X_FORWARDED_FOR',
  151. 'HTTP_X_FORWARDED_HOST',
  152. 'HTTP_X_FORWARDED_SERVER',
  153. ]
  154. def process_request(self, request):
  155. """
  156. Rewrites the proxy headers so that only the most
  157. recent proxy is used.
  158. """
  159. for field in self.FORWARDED_FOR_FIELDS:
  160. if field in request.META:
  161. if ',' in request.META[field]:
  162. parts = request.META[field].split(',')
  163. request.META[field] = parts[-1].strip()
  164. .. method:: HttpRequest.get_full_path()
  165. Returns the ``path``, plus an appended query string, if applicable.
  166. Example: ``"/music/bands/the_beatles/?print=true"``
  167. .. method:: HttpRequest.build_absolute_uri(location)
  168. Returns the absolute URI form of ``location``. If no location is provided,
  169. the location will be set to ``request.get_full_path()``.
  170. If the location is already an absolute URI, it will not be altered.
  171. Otherwise the absolute URI is built using the server variables available in
  172. this request.
  173. Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
  174. .. method:: HttpRequest.is_secure()
  175. Returns ``True`` if the request is secure; that is, if it was made with
  176. HTTPS.
  177. .. method:: HttpRequest.is_ajax()
  178. Returns ``True`` if the request was made via an ``XMLHttpRequest``, by
  179. checking the ``HTTP_X_REQUESTED_WITH`` header for the string
  180. ``'XMLHttpRequest'``. Most modern JavaScript libraries send this header.
  181. If you write your own XMLHttpRequest call (on the browser side), you'll
  182. have to set this header manually if you want ``is_ajax()`` to work.
  183. .. method:: HttpRequest.read(size=None)
  184. .. method:: HttpRequest.readline()
  185. .. method:: HttpRequest.readlines()
  186. .. method:: HttpRequest.xreadlines()
  187. .. method:: HttpRequest.__iter__()
  188. .. versionadded:: 1.3
  189. Methods implementing a file-like interface for reading from an
  190. HttpRequest instance. This makes it possible to consume an incoming
  191. request in a streaming fashion. A common use-case would be to process a
  192. big XML payload with iterative parser without constructing a whole
  193. XML tree in memory.
  194. Given this standard interface, an HttpRequest instance can be
  195. passed directly to an XML parser such as ElementTree::
  196. import xml.etree.ElementTree as ET
  197. for element in ET.iterparse(request):
  198. process(element)
  199. UploadedFile objects
  200. ====================
  201. .. class:: UploadedFile
  202. Attributes
  203. ----------
  204. .. attribute:: UploadedFile.name
  205. The name of the uploaded file.
  206. .. attribute:: UploadedFile.size
  207. The size, in bytes, of the uploaded file.
  208. Methods
  209. ----------
  210. .. method:: UploadedFile.chunks(chunk_size=None)
  211. Returns a generator that yields sequential chunks of data.
  212. .. method:: UploadedFile.read(num_bytes=None)
  213. Read a number of bytes from the file.
  214. QueryDict objects
  215. =================
  216. .. class:: QueryDict
  217. In an :class:`HttpRequest` object, the ``GET`` and ``POST`` attributes are instances
  218. of ``django.http.QueryDict``. :class:`QueryDict` is a dictionary-like
  219. class customized to deal with multiple values for the same key. This is
  220. necessary because some HTML form elements, notably
  221. ``<select multiple="multiple">``, pass multiple values for the same key.
  222. ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
  223. That means you can't change attributes of ``request.POST`` and ``request.GET``
  224. directly.
  225. Methods
  226. -------
  227. :class:`QueryDict` implements all the standard dictionary methods, because it's
  228. a subclass of dictionary. Exceptions are outlined here:
  229. .. method:: QueryDict.__getitem__(key)
  230. Returns the value for the given key. If the key has more than one value,
  231. ``__getitem__()`` returns the last value. Raises
  232. ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
  233. exist. (This is a subclass of Python's standard ``KeyError``, so you can
  234. stick to catching ``KeyError``.)
  235. .. method:: QueryDict.__setitem__(key, value)
  236. Sets the given key to ``[value]`` (a Python list whose single element is
  237. ``value``). Note that this, as other dictionary functions that have side
  238. effects, can only be called on a mutable ``QueryDict`` (one that was created
  239. via ``copy()``).
  240. .. method:: QueryDict.__contains__(key)
  241. Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
  242. in request.GET``.
  243. .. method:: QueryDict.get(key, default)
  244. Uses the same logic as ``__getitem__()`` above, with a hook for returning a
  245. default value if the key doesn't exist.
  246. .. method:: QueryDict.setdefault(key, default)
  247. Just like the standard dictionary ``setdefault()`` method, except it uses
  248. ``__setitem__()`` internally.
  249. .. method:: QueryDict.update(other_dict)
  250. Takes either a ``QueryDict`` or standard dictionary. Just like the standard
  251. dictionary ``update()`` method, except it *appends* to the current
  252. dictionary items rather than replacing them. For example::
  253. >>> q = QueryDict('a=1')
  254. >>> q = q.copy() # to make it mutable
  255. >>> q.update({'a': '2'})
  256. >>> q.getlist('a')
  257. [u'1', u'2']
  258. >>> q['a'] # returns the last
  259. [u'2']
  260. .. method:: QueryDict.items()
  261. Just like the standard dictionary ``items()`` method, except this uses the
  262. same last-value logic as ``__getitem__()``. For example::
  263. >>> q = QueryDict('a=1&a=2&a=3')
  264. >>> q.items()
  265. [(u'a', u'3')]
  266. .. method:: QueryDict.iteritems()
  267. Just like the standard dictionary ``iteritems()`` method. Like
  268. :meth:`QueryDict.items()` this uses the same last-value logic as
  269. :meth:`QueryDict.__getitem__()`.
  270. .. method:: QueryDict.iterlists()
  271. Like :meth:`QueryDict.iteritems()` except it includes all values, as a list,
  272. for each member of the dictionary.
  273. .. method:: QueryDict.values()
  274. Just like the standard dictionary ``values()`` method, except this uses the
  275. same last-value logic as ``__getitem__()``. For example::
  276. >>> q = QueryDict('a=1&a=2&a=3')
  277. >>> q.values()
  278. [u'3']
  279. .. method:: QueryDict.itervalues()
  280. Just like :meth:`QueryDict.values()`, except an iterator.
  281. In addition, ``QueryDict`` has the following methods:
  282. .. method:: QueryDict.copy()
  283. Returns a copy of the object, using ``copy.deepcopy()`` from the Python
  284. standard library. The copy will be mutable -- that is, you can change its
  285. values.
  286. .. method:: QueryDict.getlist(key)
  287. Returns the data with the requested key, as a Python list. Returns an
  288. empty list if the key doesn't exist. It's guaranteed to return a list of
  289. some sort.
  290. .. method:: QueryDict.setlist(key, list_)
  291. Sets the given key to ``list_`` (unlike ``__setitem__()``).
  292. .. method:: QueryDict.appendlist(key, item)
  293. Appends an item to the internal list associated with key.
  294. .. method:: QueryDict.setlistdefault(key, default_list)
  295. Just like ``setdefault``, except it takes a list of values instead of a
  296. single value.
  297. .. method:: QueryDict.lists()
  298. Like :meth:`items()`, except it includes all values, as a list, for each
  299. member of the dictionary. For example::
  300. >>> q = QueryDict('a=1&a=2&a=3')
  301. >>> q.lists()
  302. [(u'a', [u'1', u'2', u'3'])]
  303. .. method:: QueryDict.urlencode([safe])
  304. Returns a string of the data in query-string format. Example::
  305. >>> q = QueryDict('a=2&b=3&b=5')
  306. >>> q.urlencode()
  307. 'a=2&b=3&b=5'
  308. .. versionchanged:: 1.3
  309. The ``safe`` parameter was added.
  310. Optionally, urlencode can be passed characters which
  311. do not require encoding. For example::
  312. >>> q = QueryDict('', mutable=True)
  313. >>> q['next'] = '/a&b/'
  314. >>> q.urlencode(safe='/')
  315. 'next=/a%26b/'
  316. HttpResponse objects
  317. ====================
  318. .. class:: HttpResponse
  319. In contrast to :class:`HttpRequest` objects, which are created automatically by
  320. Django, :class:`HttpResponse` objects are your responsibility. Each view you
  321. write is responsible for instantiating, populating and returning an
  322. :class:`HttpResponse`.
  323. The :class:`HttpResponse` class lives in the :mod:`django.http` module.
  324. Usage
  325. -----
  326. Passing strings
  327. ~~~~~~~~~~~~~~~
  328. Typical usage is to pass the contents of the page, as a string, to the
  329. :class:`HttpResponse` constructor::
  330. >>> response = HttpResponse("Here's the text of the Web page.")
  331. >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
  332. But if you want to add content incrementally, you can use ``response`` as a
  333. file-like object::
  334. >>> response = HttpResponse()
  335. >>> response.write("<p>Here's the text of the Web page.</p>")
  336. >>> response.write("<p>Here's another paragraph.</p>")
  337. Passing iterators
  338. ~~~~~~~~~~~~~~~~~
  339. Finally, you can pass ``HttpResponse`` an iterator rather than passing it
  340. hard-coded strings. If you use this technique, follow these guidelines:
  341. * The iterator should return strings.
  342. * If an :class:`HttpResponse` has been initialized with an iterator as its
  343. content, you can't use the :class:`HttpResponse` instance as a file-like
  344. object. Doing so will raise ``Exception``.
  345. Setting headers
  346. ~~~~~~~~~~~~~~~
  347. To set or remove a header in your response, treat it like a dictionary::
  348. >>> response = HttpResponse()
  349. >>> response['Cache-Control'] = 'no-cache'
  350. >>> del response['Cache-Control']
  351. Note that unlike a dictionary, ``del`` doesn't raise ``KeyError`` if the header
  352. doesn't exist.
  353. HTTP headers cannot contain newlines. An attempt to set a header containing a
  354. newline character (CR or LF) will raise ``BadHeaderError``
  355. Telling the browser to treat the response as a file attachment
  356. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  357. To tell the browser to treat the response as a file attachment, use the
  358. ``mimetype`` argument and set the ``Content-Disposition`` header. For example,
  359. this is how you might return a Microsoft Excel spreadsheet::
  360. >>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
  361. >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
  362. There's nothing Django-specific about the ``Content-Disposition`` header, but
  363. it's easy to forget the syntax, so we've included it here.
  364. Attributes
  365. ----------
  366. .. attribute:: HttpResponse.content
  367. A normal Python string representing the content, encoded from a Unicode
  368. object if necessary.
  369. .. attribute:: HttpResponse.status_code
  370. The `HTTP Status code`_ for the response.
  371. Methods
  372. -------
  373. .. method:: HttpResponse.__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE)
  374. Instantiates an ``HttpResponse`` object with the given page content (a
  375. string) and MIME type. The :setting:`DEFAULT_CONTENT_TYPE` is
  376. ``'text/html'``.
  377. ``content`` can be an iterator or a string. If it's an iterator, it should
  378. return strings, and those strings will be joined together to form the
  379. content of the response.
  380. ``status`` is the `HTTP Status code`_ for the response.
  381. ``content_type`` is an alias for ``mimetype``. Historically, this parameter
  382. was only called ``mimetype``, but since this is actually the value included
  383. in the HTTP ``Content-Type`` header, it can also include the character set
  384. encoding, which makes it more than just a MIME type specification.
  385. If ``mimetype`` is specified (not ``None``), that value is used.
  386. Otherwise, ``content_type`` is used. If neither is given, the
  387. :setting:`DEFAULT_CONTENT_TYPE` setting is used.
  388. .. method:: HttpResponse.__setitem__(header, value)
  389. Sets the given header name to the given value. Both ``header`` and
  390. ``value`` should be strings.
  391. .. method:: HttpResponse.__delitem__(header)
  392. Deletes the header with the given name. Fails silently if the header
  393. doesn't exist. Case-insensitive.
  394. .. method:: HttpResponse.__getitem__(header)
  395. Returns the value for the given header name. Case-insensitive.
  396. .. method:: HttpResponse.has_header(header)
  397. Returns ``True`` or ``False`` based on a case-insensitive check for a
  398. header with the given name.
  399. .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)
  400. .. versionchanged:: 1.3
  401. The possibility of specifying a ``datetime.datetime`` object in
  402. ``expires``, and the auto-calculation of ``max_age`` in such case
  403. was added. The ``httponly`` argument was also added.
  404. Sets a cookie. The parameters are the same as in the `cookie Morsel`_
  405. object in the Python standard library.
  406. * ``max_age`` should be a number of seconds, or ``None`` (default) if
  407. the cookie should last only as long as the client's browser session.
  408. If ``expires`` is not specified, it will be calculated.
  409. * ``expires`` should either be a string in the format
  410. ``"Wdy, DD-Mon-YY HH:MM:SS GMT"`` or a ``datetime.datetime`` object
  411. in UTC. If ``expires`` is a ``datetime`` object, the ``max_age``
  412. will be calculated.
  413. * Use ``domain`` if you want to set a cross-domain cookie. For example,
  414. ``domain=".lawrence.com"`` will set a cookie that is readable by
  415. the domains www.lawrence.com, blogs.lawrence.com and
  416. calendars.lawrence.com. Otherwise, a cookie will only be readable by
  417. the domain that set it.
  418. * Use ``httponly=True`` if you want to prevent client-side
  419. JavaScript from having access to the cookie.
  420. HTTPOnly_ is a flag included in a Set-Cookie HTTP response
  421. header. It is not part of the RFC2109 standard for cookies,
  422. and it isn't honored consistently by all browsers. However,
  423. when it is honored, it can be a useful way to mitigate the
  424. risk of client side script accessing the protected cookie
  425. data.
  426. .. _`cookie Morsel`: http://docs.python.org/library/cookie.html#Cookie.Morsel
  427. .. _HTTPOnly: http://www.owasp.org/index.php/HTTPOnly
  428. .. method:: HttpResponse.delete_cookie(key, path='/', domain=None)
  429. Deletes the cookie with the given key. Fails silently if the key doesn't
  430. exist.
  431. Due to the way cookies work, ``path`` and ``domain`` should be the same
  432. values you used in ``set_cookie()`` -- otherwise the cookie may not be
  433. deleted.
  434. .. method:: HttpResponse.write(content)
  435. This method makes an :class:`HttpResponse` instance a file-like object.
  436. .. method:: HttpResponse.flush()
  437. This method makes an :class:`HttpResponse` instance a file-like object.
  438. .. method:: HttpResponse.tell()
  439. This method makes an :class:`HttpResponse` instance a file-like object.
  440. .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
  441. .. _ref-httpresponse-subclasses:
  442. HttpResponse subclasses
  443. -----------------------
  444. Django includes a number of ``HttpResponse`` subclasses that handle different
  445. types of HTTP responses. Like ``HttpResponse``, these subclasses live in
  446. :mod:`django.http`.
  447. .. class:: HttpResponseRedirect
  448. The constructor takes a single argument -- the path to redirect to. This
  449. can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or
  450. an absolute path with no domain (e.g. ``'/search/'``). Note that this
  451. returns an HTTP status code 302.
  452. .. class:: HttpResponsePermanentRedirect
  453. Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
  454. (HTTP status code 301) instead of a "found" redirect (status code 302).
  455. .. class:: HttpResponseNotModified
  456. The constructor doesn't take any arguments. Use this to designate that a
  457. page hasn't been modified since the user's last request (status code 304).
  458. .. class:: HttpResponseBadRequest
  459. Acts just like :class:`HttpResponse` but uses a 400 status code.
  460. .. class:: HttpResponseNotFound
  461. Acts just like :class:`HttpResponse` but uses a 404 status code.
  462. .. class:: HttpResponseForbidden
  463. Acts just like :class:`HttpResponse` but uses a 403 status code.
  464. .. class:: HttpResponseNotAllowed
  465. Like :class:`HttpResponse`, but uses a 405 status code. Takes a single,
  466. required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
  467. .. class:: HttpResponseGone
  468. Acts just like :class:`HttpResponse` but uses a 410 status code.
  469. .. class:: HttpResponseServerError
  470. Acts just like :class:`HttpResponse` but uses a 500 status code.