<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang=""> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Request and response objects — Django 1.8.19 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '1.8.19', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="top" title="Django 1.8.19 documentation" href="../contents.html" /> <link rel="up" title="API Reference" href="index.html" /> <link rel="next" title="SchemaEditor" href="schema-editor.html" /> <link rel="prev" title="Database Functions" href="models/database-functions.html" /> <script type="text/javascript" src="../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head> <body role="document"> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../index.html">Django 1.8.19 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../index.html">Home</a> | <a title="Table of contents" href="../contents.html">Table of contents</a> | <a title="Global index" href="../genindex.html">Index</a> | <a title="Module index" href="../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="models/database-functions.html" title="Database Functions">previous</a> | <a href="index.html" title="API Reference" accesskey="U">up</a> | <a href="schema-editor.html" title="<code class="docutils literal"><span class="pre">SchemaEditor</span></code>">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="ref-request-response"> <div class="section" id="s-module-django.http"> <span id="s-request-and-response-objects"></span><span id="module-django.http"></span><span id="request-and-response-objects"></span><h1>Request and response objects<a class="headerlink" href="#module-django.http" title="Permalink to this headline">¶</a></h1> <div class="section" id="s-quick-overview"> <span id="quick-overview"></span><h2>Quick overview<a class="headerlink" href="#quick-overview" title="Permalink to this headline">¶</a></h2> <p>Django uses request and response objects to pass state through the system.</p> <p>When a page is requested, Django creates an <a class="reference internal" href="#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> object that contains metadata about the request. Then Django loads the appropriate view, passing the <a class="reference internal" href="#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> as the first argument to the view function. Each view is responsible for returning an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> object.</p> <p>This document explains the APIs for <a class="reference internal" href="#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> and <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> objects, which are defined in the <a class="reference internal" href="#module-django.http" title="django.http: Classes dealing with HTTP requests and responses."><code class="xref py py-mod docutils literal"><span class="pre">django.http</span></code></a> module.</p> </div> <div class="section" id="s-httprequest-objects"> <span id="httprequest-objects"></span><h2>HttpRequest objects<a class="headerlink" href="#httprequest-objects" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="django.http.HttpRequest"> <em class="property">class </em><code class="descname">HttpRequest</code><a class="reference internal" href="../_modules/django/http/request.html#HttpRequest"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="section" id="s-attributes"> <span id="s-httprequest-attributes"></span><span id="attributes"></span><span id="httprequest-attributes"></span><h3>Attributes<a class="headerlink" href="#attributes" title="Permalink to this headline">¶</a></h3> <p>All attributes should be considered read-only, unless stated otherwise.</p> <dl class="attribute"> <dt id="django.http.HttpRequest.scheme"> <code class="descclassname">HttpRequest.</code><code class="descname">scheme</code><a class="headerlink" href="#django.http.HttpRequest.scheme" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.7.</span> </div> <p>A string representing the scheme of the request (<code class="docutils literal"><span class="pre">http</span></code> or <code class="docutils literal"><span class="pre">https</span></code> usually).</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.body"> <code class="descclassname">HttpRequest.</code><code class="descname">body</code><a class="headerlink" href="#django.http.HttpRequest.body" title="Permalink to this definition">¶</a></dt> <dd><p>The raw HTTP request body as a byte string. This is useful for processing data in different ways than conventional HTML forms: binary images, XML payload etc. For processing conventional form data, use <code class="docutils literal"><span class="pre">HttpRequest.POST</span></code>.</p> <p>You can also read from an HttpRequest using a file-like interface. See <a class="reference internal" href="#django.http.HttpRequest.read" title="django.http.HttpRequest.read"><code class="xref py py-meth docutils literal"><span class="pre">HttpRequest.read()</span></code></a>.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.path"> <code class="descclassname">HttpRequest.</code><code class="descname">path</code><a class="headerlink" href="#django.http.HttpRequest.path" title="Permalink to this definition">¶</a></dt> <dd><p>A string representing the full path to the requested page, not including the scheme or domain.</p> <p>Example: <code class="docutils literal"><span class="pre">"/music/bands/the_beatles/"</span></code></p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.path_info"> <code class="descclassname">HttpRequest.</code><code class="descname">path_info</code><a class="headerlink" href="#django.http.HttpRequest.path_info" title="Permalink to this definition">¶</a></dt> <dd><p>Under some Web server configurations, the portion of the URL after the host name is split up into a script prefix portion and a path info portion. The <code class="docutils literal"><span class="pre">path_info</span></code> attribute always contains the path info portion of the path, no matter what Web server is being used. Using this instead of <a class="reference internal" href="#django.http.HttpRequest.path" title="django.http.HttpRequest.path"><code class="xref py py-attr docutils literal"><span class="pre">path</span></code></a> can make your code easier to move between test and deployment servers.</p> <p>For example, if the <code class="docutils literal"><span class="pre">WSGIScriptAlias</span></code> for your application is set to <code class="docutils literal"><span class="pre">"/minfo"</span></code>, then <code class="docutils literal"><span class="pre">path</span></code> might be <code class="docutils literal"><span class="pre">"/minfo/music/bands/the_beatles/"</span></code> and <code class="docutils literal"><span class="pre">path_info</span></code> would be <code class="docutils literal"><span class="pre">"/music/bands/the_beatles/"</span></code>.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.method"> <code class="descclassname">HttpRequest.</code><code class="descname">method</code><a class="headerlink" href="#django.http.HttpRequest.method" title="Permalink to this definition">¶</a></dt> <dd><p>A string representing the HTTP method used in the request. This is guaranteed to be uppercase. Example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s1">'GET'</span><span class="p">:</span> <span class="n">do_something</span><span class="p">()</span> <span class="k">elif</span> <span class="n">request</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s1">'POST'</span><span class="p">:</span> <span class="n">do_something_else</span><span class="p">()</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.encoding"> <code class="descclassname">HttpRequest.</code><code class="descname">encoding</code><a class="headerlink" href="#django.http.HttpRequest.encoding" title="Permalink to this definition">¶</a></dt> <dd><p>A string representing the current encoding used to decode form submission data (or <code class="docutils literal"><span class="pre">None</span></code>, which means the <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CHARSET</span></code></a> setting is used). You can write to this attribute to change the encoding used when accessing the form data. Any subsequent attribute accesses (such as reading from <code class="docutils literal"><span class="pre">GET</span></code> or <code class="docutils literal"><span class="pre">POST</span></code>) will use the new <code class="docutils literal"><span class="pre">encoding</span></code> value. Useful if you know the form data is not in the <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CHARSET</span></code></a> encoding.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.GET"> <code class="descclassname">HttpRequest.</code><code class="descname">GET</code><a class="headerlink" href="#django.http.HttpRequest.GET" title="Permalink to this definition">¶</a></dt> <dd><p>A dictionary-like object containing all given HTTP GET parameters. See the <a class="reference internal" href="#django.http.QueryDict" title="django.http.QueryDict"><code class="xref py py-class docutils literal"><span class="pre">QueryDict</span></code></a> documentation below.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.POST"> <code class="descclassname">HttpRequest.</code><code class="descname">POST</code><a class="headerlink" href="#django.http.HttpRequest.POST" title="Permalink to this definition">¶</a></dt> <dd><p>A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the <a class="reference internal" href="#django.http.QueryDict" title="django.http.QueryDict"><code class="xref py py-class docutils literal"><span class="pre">QueryDict</span></code></a> documentation below. If you need to access raw or non-form data posted in the request, access this through the <a class="reference internal" href="#django.http.HttpRequest.body" title="django.http.HttpRequest.body"><code class="xref py py-attr docutils literal"><span class="pre">HttpRequest.body</span></code></a> attribute instead.</p> <p>It’s possible that a request can come in via POST with an empty <code class="docutils literal"><span class="pre">POST</span></code> dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t use <code class="docutils literal"><span class="pre">if</span> <span class="pre">request.POST</span></code> to check for use of the POST method; instead, use <code class="docutils literal"><span class="pre">if</span> <span class="pre">request.method</span> <span class="pre">==</span> <span class="pre">"POST"</span></code> (see above).</p> <p>Note: <code class="docutils literal"><span class="pre">POST</span></code> does <em>not</em> include file-upload information. See <code class="docutils literal"><span class="pre">FILES</span></code>.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.REQUEST"> <code class="descclassname">HttpRequest.</code><code class="descname">REQUEST</code><a class="headerlink" href="#django.http.HttpRequest.REQUEST" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.7: </span>Use the more explicit <code class="docutils literal"><span class="pre">GET</span></code> and <code class="docutils literal"><span class="pre">POST</span></code> instead.</p> </div> <p>For convenience, a dictionary-like object that searches <code class="docutils literal"><span class="pre">POST</span></code> first, then <code class="docutils literal"><span class="pre">GET</span></code>. Inspired by PHP’s <code class="docutils literal"><span class="pre">$_REQUEST</span></code>.</p> <p>For example, if <code class="docutils literal"><span class="pre">GET</span> <span class="pre">=</span> <span class="pre">{"name":</span> <span class="pre">"john"}</span></code> and <code class="docutils literal"><span class="pre">POST</span> <span class="pre">=</span> <span class="pre">{"age":</span> <span class="pre">'34'}</span></code>, <code class="docutils literal"><span class="pre">REQUEST["name"]</span></code> would be <code class="docutils literal"><span class="pre">"john"</span></code>, and <code class="docutils literal"><span class="pre">REQUEST["age"]</span></code> would be <code class="docutils literal"><span class="pre">"34"</span></code>.</p> <p>It’s strongly suggested that you use <code class="docutils literal"><span class="pre">GET</span></code> and <code class="docutils literal"><span class="pre">POST</span></code> instead of <code class="docutils literal"><span class="pre">REQUEST</span></code>, because the former are more explicit.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.COOKIES"> <code class="descclassname">HttpRequest.</code><code class="descname">COOKIES</code><a class="headerlink" href="#django.http.HttpRequest.COOKIES" title="Permalink to this definition">¶</a></dt> <dd><p>A standard Python dictionary containing all cookies. Keys and values are strings.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.FILES"> <code class="descclassname">HttpRequest.</code><code class="descname">FILES</code><a class="headerlink" href="#django.http.HttpRequest.FILES" title="Permalink to this definition">¶</a></dt> <dd><p>A dictionary-like object containing all uploaded files. Each key in <code class="docutils literal"><span class="pre">FILES</span></code> is the <code class="docutils literal"><span class="pre">name</span></code> from the <code class="docutils literal"><span class="pre"><input</span> <span class="pre">type="file"</span> <span class="pre">name=""</span> <span class="pre">/></span></code>. Each value in <code class="docutils literal"><span class="pre">FILES</span></code> is an <a class="reference internal" href="files/uploads.html#django.core.files.uploadedfile.UploadedFile" title="django.core.files.uploadedfile.UploadedFile"><code class="xref py py-class docutils literal"><span class="pre">UploadedFile</span></code></a>.</p> <p>See <a class="reference internal" href="../topics/files.html"><span class="doc">Managing files</span></a> for more information.</p> <p>Note that <code class="docutils literal"><span class="pre">FILES</span></code> will only contain data if the request method was POST and the <code class="docutils literal"><span class="pre"><form></span></code> that posted to the request had <code class="docutils literal"><span class="pre">enctype="multipart/form-data"</span></code>. Otherwise, <code class="docutils literal"><span class="pre">FILES</span></code> will be a blank dictionary-like object.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.META"> <code class="descclassname">HttpRequest.</code><code class="descname">META</code><a class="headerlink" href="#django.http.HttpRequest.META" title="Permalink to this definition">¶</a></dt> <dd><p>A standard Python dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:</p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">CONTENT_LENGTH</span></code> – The length of the request body (as a string).</li> <li><code class="docutils literal"><span class="pre">CONTENT_TYPE</span></code> – The MIME type of the request body.</li> <li><code class="docutils literal"><span class="pre">HTTP_ACCEPT</span></code> – Acceptable content types for the response.</li> <li><code class="docutils literal"><span class="pre">HTTP_ACCEPT_ENCODING</span></code> – Acceptable encodings for the response.</li> <li><code class="docutils literal"><span class="pre">HTTP_ACCEPT_LANGUAGE</span></code> – Acceptable languages for the response.</li> <li><code class="docutils literal"><span class="pre">HTTP_HOST</span></code> – The HTTP Host header sent by the client.</li> <li><code class="docutils literal"><span class="pre">HTTP_REFERER</span></code> – The referring page, if any.</li> <li><code class="docutils literal"><span class="pre">HTTP_USER_AGENT</span></code> – The client’s user-agent string.</li> <li><code class="docutils literal"><span class="pre">QUERY_STRING</span></code> – The query string, as a single (unparsed) string.</li> <li><code class="docutils literal"><span class="pre">REMOTE_ADDR</span></code> – The IP address of the client.</li> <li><code class="docutils literal"><span class="pre">REMOTE_HOST</span></code> – The hostname of the client.</li> <li><code class="docutils literal"><span class="pre">REMOTE_USER</span></code> – The user authenticated by the Web server, if any.</li> <li><code class="docutils literal"><span class="pre">REQUEST_METHOD</span></code> – A string such as <code class="docutils literal"><span class="pre">"GET"</span></code> or <code class="docutils literal"><span class="pre">"POST"</span></code>.</li> <li><code class="docutils literal"><span class="pre">SERVER_NAME</span></code> – The hostname of the server.</li> <li><code class="docutils literal"><span class="pre">SERVER_PORT</span></code> – The port of the server (as a string).</li> </ul> <p>With the exception of <code class="docutils literal"><span class="pre">CONTENT_LENGTH</span></code> and <code class="docutils literal"><span class="pre">CONTENT_TYPE</span></code>, as given above, any HTTP headers in the request are converted to <code class="docutils literal"><span class="pre">META</span></code> keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an <code class="docutils literal"><span class="pre">HTTP_</span></code> prefix to the name. So, for example, a header called <code class="docutils literal"><span class="pre">X-Bender</span></code> would be mapped to the <code class="docutils literal"><span class="pre">META</span></code> key <code class="docutils literal"><span class="pre">HTTP_X_BENDER</span></code>.</p> <p>Note that <a class="reference internal" href="django-admin.html#django-admin-runserver"><code class="xref std std-djadmin docutils literal"><span class="pre">runserver</span></code></a> strips all headers with underscores in the name, so you won’t see them in <code class="docutils literal"><span class="pre">META</span></code>. This prevents header-spoofing based on ambiguity between underscores and dashes both being normalizing to underscores in WSGI environment variables. It matches the behavior of Web servers like Nginx and Apache 2.4+.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.urlconf"> <code class="descclassname">HttpRequest.</code><code class="descname">urlconf</code><a class="headerlink" href="#django.http.HttpRequest.urlconf" title="Permalink to this definition">¶</a></dt> <dd><p>Not defined by Django itself, but will be read if other code (e.g., a custom middleware class) sets it. When present, this will be used as the root URLconf for the current request, overriding the <a class="reference internal" href="settings.html#std:setting-ROOT_URLCONF"><code class="xref std std-setting docutils literal"><span class="pre">ROOT_URLCONF</span></code></a> setting. See <a class="reference internal" href="../topics/http/urls.html#how-django-processes-a-request"><span class="std std-ref">How Django processes a request</span></a> for details.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.resolver_match"> <code class="descclassname">HttpRequest.</code><code class="descname">resolver_match</code><a class="headerlink" href="#django.http.HttpRequest.resolver_match" title="Permalink to this definition">¶</a></dt> <dd><p>An instance of <a class="reference internal" href="urlresolvers.html#django.core.urlresolvers.ResolverMatch" title="django.core.urlresolvers.ResolverMatch"><code class="xref py py-class docutils literal"><span class="pre">ResolverMatch</span></code></a> representing the resolved url. This attribute is only set after url resolving took place, which means it’s available in all views but not in middleware methods which are executed before url resolving takes place (like <code class="docutils literal"><span class="pre">process_request</span></code>, you can use <code class="docutils literal"><span class="pre">process_view</span></code> instead).</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.current_app"> <code class="descclassname">HttpRequest.</code><code class="descname">current_app</code><a class="headerlink" href="#django.http.HttpRequest.current_app" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p>Not defined by Django itself, but if set, the <a class="reference internal" href="templates/builtins.html#std:templatetag-url"><code class="xref std std-ttag docutils literal"><span class="pre">url</span></code></a> template tag will use its value as the <code class="docutils literal"><span class="pre">current_app</span></code> argument to <a class="reference internal" href="urlresolvers.html#django.core.urlresolvers.reverse" title="django.core.urlresolvers.reverse"><code class="xref py py-func docutils literal"><span class="pre">reverse()</span></code></a>.</p> </dd></dl> </div> <div class="section" id="s-attributes-set-by-middleware"> <span id="attributes-set-by-middleware"></span><h3>Attributes set by middleware<a class="headerlink" href="#attributes-set-by-middleware" title="Permalink to this headline">¶</a></h3> <p>Some of the middleware included in Django’s contrib apps set attributes on the request. If you don’t see the attribute on a request, be sure the appropriate middleware class is listed in <a class="reference internal" href="settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a>.</p> <dl class="attribute"> <dt id="django.http.HttpRequest.session"> <code class="descclassname">HttpRequest.</code><code class="descname">session</code><a class="headerlink" href="#django.http.HttpRequest.session" title="Permalink to this definition">¶</a></dt> <dd><p>From the <a class="reference internal" href="middleware.html#django.contrib.sessions.middleware.SessionMiddleware" title="django.contrib.sessions.middleware.SessionMiddleware"><code class="xref py py-class docutils literal"><span class="pre">SessionMiddleware</span></code></a>: A readable and writable, dictionary-like object that represents the current session.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.site"> <code class="descclassname">HttpRequest.</code><code class="descname">site</code><a class="headerlink" href="#django.http.HttpRequest.site" title="Permalink to this definition">¶</a></dt> <dd><p>From the <a class="reference internal" href="middleware.html#django.contrib.sites.middleware.CurrentSiteMiddleware" title="django.contrib.sites.middleware.CurrentSiteMiddleware"><code class="xref py py-class docutils literal"><span class="pre">CurrentSiteMiddleware</span></code></a>: An instance of <a class="reference internal" href="contrib/sites.html#django.contrib.sites.models.Site" title="django.contrib.sites.models.Site"><code class="xref py py-class docutils literal"><span class="pre">Site</span></code></a> or <a class="reference internal" href="contrib/sites.html#django.contrib.sites.requests.RequestSite" title="django.contrib.sites.requests.RequestSite"><code class="xref py py-class docutils literal"><span class="pre">RequestSite</span></code></a> as returned by <a class="reference internal" href="contrib/sites.html#django.contrib.sites.shortcuts.get_current_site" title="django.contrib.sites.shortcuts.get_current_site"><code class="xref py py-func docutils literal"><span class="pre">get_current_site()</span></code></a> representing the current site.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpRequest.user"> <code class="descclassname">HttpRequest.</code><code class="descname">user</code><a class="headerlink" href="#django.http.HttpRequest.user" title="Permalink to this definition">¶</a></dt> <dd><p>From the <a class="reference internal" href="middleware.html#django.contrib.auth.middleware.AuthenticationMiddleware" title="django.contrib.auth.middleware.AuthenticationMiddleware"><code class="xref py py-class docutils literal"><span class="pre">AuthenticationMiddleware</span></code></a>: An instance of <a class="reference internal" href="settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal"><span class="pre">AUTH_USER_MODEL</span></code></a> representing the currently logged-in user. If the user isn’t currently logged in, <code class="docutils literal"><span class="pre">user</span></code> will be set to an instance of <a class="reference internal" href="contrib/auth.html#django.contrib.auth.models.AnonymousUser" title="django.contrib.auth.models.AnonymousUser"><code class="xref py py-class docutils literal"><span class="pre">AnonymousUser</span></code></a>. You can tell them apart with <a class="reference internal" href="contrib/auth.html#django.contrib.auth.models.User.is_authenticated" title="django.contrib.auth.models.User.is_authenticated"><code class="xref py py-meth docutils literal"><span class="pre">is_authenticated()</span></code></a>, like so:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">is_authenticated</span><span class="p">():</span> <span class="o">...</span> <span class="c1"># Do something for logged-in users.</span> <span class="k">else</span><span class="p">:</span> <span class="o">...</span> <span class="c1"># Do something for anonymous users.</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="s-methods"> <span id="methods"></span><h3>Methods<a class="headerlink" href="#methods" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="django.http.HttpRequest.get_host"> <code class="descclassname">HttpRequest.</code><code class="descname">get_host</code>()<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.get_host"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.get_host" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the originating host of the request using information from the <code class="docutils literal"><span class="pre">HTTP_X_FORWARDED_HOST</span></code> (if <a class="reference internal" href="settings.html#std:setting-USE_X_FORWARDED_HOST"><code class="xref std std-setting docutils literal"><span class="pre">USE_X_FORWARDED_HOST</span></code></a> is enabled) and <code class="docutils literal"><span class="pre">HTTP_HOST</span></code> headers, in that order. If they don’t provide a value, the method uses a combination of <code class="docutils literal"><span class="pre">SERVER_NAME</span></code> and <code class="docutils literal"><span class="pre">SERVER_PORT</span></code> as detailed in <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3333"><strong>PEP 3333</strong></a>.</p> <p>Example: <code class="docutils literal"><span class="pre">"127.0.0.1:8000"</span></code></p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>The <a class="reference internal" href="#django.http.HttpRequest.get_host" title="django.http.HttpRequest.get_host"><code class="xref py py-meth docutils literal"><span class="pre">get_host()</span></code></a> method fails when the host is behind multiple proxies. One solution is to use middleware to rewrite the proxy headers, as in the following example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MultipleProxyMiddleware</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="n">FORWARDED_FOR_FIELDS</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">'HTTP_X_FORWARDED_FOR'</span><span class="p">,</span> <span class="s1">'HTTP_X_FORWARDED_HOST'</span><span class="p">,</span> <span class="s1">'HTTP_X_FORWARDED_SERVER'</span><span class="p">,</span> <span class="p">]</span> <span class="k">def</span> <span class="nf">process_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> Rewrites the proxy headers so that only the most</span> <span class="sd"> recent proxy is used.</span> <span class="sd"> """</span> <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">FORWARDED_FOR_FIELDS</span><span class="p">:</span> <span class="k">if</span> <span class="n">field</span> <span class="ow">in</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="p">:</span> <span class="k">if</span> <span class="s1">','</span> <span class="ow">in</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="p">[</span><span class="n">field</span><span class="p">]:</span> <span class="n">parts</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="p">[</span><span class="n">field</span><span class="p">]</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">','</span><span class="p">)</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="p">[</span><span class="n">field</span><span class="p">]</span> <span class="o">=</span> <span class="n">parts</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> </pre></div> </div> <p class="last">This middleware should be positioned before any other middleware that relies on the value of <a class="reference internal" href="#django.http.HttpRequest.get_host" title="django.http.HttpRequest.get_host"><code class="xref py py-meth docutils literal"><span class="pre">get_host()</span></code></a> – for instance, <a class="reference internal" href="middleware.html#django.middleware.common.CommonMiddleware" title="django.middleware.common.CommonMiddleware"><code class="xref py py-class docutils literal"><span class="pre">CommonMiddleware</span></code></a> or <a class="reference internal" href="middleware.html#django.middleware.csrf.CsrfViewMiddleware" title="django.middleware.csrf.CsrfViewMiddleware"><code class="xref py py-class docutils literal"><span class="pre">CsrfViewMiddleware</span></code></a>.</p> </div> </dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.get_full_path"> <code class="descclassname">HttpRequest.</code><code class="descname">get_full_path</code>()<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.get_full_path"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.get_full_path" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the <code class="docutils literal"><span class="pre">path</span></code>, plus an appended query string, if applicable.</p> <p>Example: <code class="docutils literal"><span class="pre">"/music/bands/the_beatles/?print=true"</span></code></p> </dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.build_absolute_uri"> <code class="descclassname">HttpRequest.</code><code class="descname">build_absolute_uri</code>(<em>location</em>)<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.build_absolute_uri"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.build_absolute_uri" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the absolute URI form of <code class="docutils literal"><span class="pre">location</span></code>. If no location is provided, the location will be set to <code class="docutils literal"><span class="pre">request.get_full_path()</span></code>.</p> <p>If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request.</p> <p>Example: <code class="docutils literal"><span class="pre">"http://example.com/music/bands/the_beatles/?print=true"</span></code></p> </dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.get_signed_cookie"> <code class="descclassname">HttpRequest.</code><code class="descname">get_signed_cookie</code>(<em>key</em>, <em>default=RAISE_ERROR</em>, <em>salt=''</em>, <em>max_age=None</em>)<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.get_signed_cookie"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.get_signed_cookie" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a cookie value for a signed cookie, or raises a <code class="docutils literal"><span class="pre">django.core.signing.BadSignature</span></code> exception if the signature is no longer valid. If you provide the <code class="docutils literal"><span class="pre">default</span></code> argument the exception will be suppressed and that default value will be returned instead.</p> <p>The optional <code class="docutils literal"><span class="pre">salt</span></code> argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the <code class="docutils literal"><span class="pre">max_age</span></code> argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than <code class="docutils literal"><span class="pre">max_age</span></code> seconds.</p> <p>For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">request</span><span class="o">.</span><span class="n">get_signed_cookie</span><span class="p">(</span><span class="s1">'name'</span><span class="p">)</span> <span class="go">'Tony'</span> <span class="gp">>>> </span><span class="n">request</span><span class="o">.</span><span class="n">get_signed_cookie</span><span class="p">(</span><span class="s1">'name'</span><span class="p">,</span> <span class="n">salt</span><span class="o">=</span><span class="s1">'name-salt'</span><span class="p">)</span> <span class="go">'Tony' # assuming cookie was set using the same salt</span> <span class="gp">>>> </span><span class="n">request</span><span class="o">.</span><span class="n">get_signed_cookie</span><span class="p">(</span><span class="s1">'non-existing-cookie'</span><span class="p">)</span> <span class="gp">...</span> <span class="go">KeyError: 'non-existing-cookie'</span> <span class="gp">>>> </span><span class="n">request</span><span class="o">.</span><span class="n">get_signed_cookie</span><span class="p">(</span><span class="s1">'non-existing-cookie'</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">request</span><span class="o">.</span><span class="n">get_signed_cookie</span><span class="p">(</span><span class="s1">'cookie-that-was-tampered-with'</span><span class="p">)</span> <span class="gp">...</span> <span class="go">BadSignature: ...</span> <span class="gp">>>> </span><span class="n">request</span><span class="o">.</span><span class="n">get_signed_cookie</span><span class="p">(</span><span class="s1">'name'</span><span class="p">,</span> <span class="n">max_age</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span> <span class="gp">...</span> <span class="go">SignatureExpired: Signature age 1677.3839159 > 60 seconds</span> <span class="gp">>>> </span><span class="n">request</span><span class="o">.</span><span class="n">get_signed_cookie</span><span class="p">(</span><span class="s1">'name'</span><span class="p">,</span> <span class="kc">False</span><span class="p">,</span> <span class="n">max_age</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span> <span class="go">False</span> </pre></div> </div> <p>See <a class="reference internal" href="../topics/signing.html"><span class="doc">cryptographic signing</span></a> for more information.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.is_secure"> <code class="descclassname">HttpRequest.</code><code class="descname">is_secure</code>()<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.is_secure"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.is_secure" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal"><span class="pre">True</span></code> if the request is secure; that is, if it was made with HTTPS.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.is_ajax"> <code class="descclassname">HttpRequest.</code><code class="descname">is_ajax</code>()<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.is_ajax"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.is_ajax" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal"><span class="pre">True</span></code> if the request was made via an <code class="docutils literal"><span class="pre">XMLHttpRequest</span></code>, by checking the <code class="docutils literal"><span class="pre">HTTP_X_REQUESTED_WITH</span></code> header for the string <code class="docutils literal"><span class="pre">'XMLHttpRequest'</span></code>. Most modern JavaScript libraries send this header. If you write your own XMLHttpRequest call (on the browser side), you’ll have to set this header manually if you want <code class="docutils literal"><span class="pre">is_ajax()</span></code> to work.</p> <p>If a response varies on whether or not it’s requested via AJAX and you are using some form of caching like Django’s <a class="reference internal" href="middleware.html#module-django.middleware.cache" title="django.middleware.cache: Middleware for the site-wide cache."><code class="xref py py-mod docutils literal"><span class="pre">cache</span> <span class="pre">middleware</span></code></a>, you should decorate the view with <a class="reference internal" href="../topics/http/decorators.html#django.views.decorators.vary.vary_on_headers" title="django.views.decorators.vary.vary_on_headers"><code class="xref py py-func docutils literal"><span class="pre">vary_on_headers('X-Requested-With')</span></code></a> so that the responses are properly cached.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.read"> <code class="descclassname">HttpRequest.</code><code class="descname">read</code>(<em>size=None</em>)<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.read"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.read" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.readline"> <code class="descclassname">HttpRequest.</code><code class="descname">readline</code>()<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.readline"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.readline" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.readlines"> <code class="descclassname">HttpRequest.</code><code class="descname">readlines</code>()<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.readlines"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.readlines" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.xreadlines"> <code class="descclassname">HttpRequest.</code><code class="descname">xreadlines</code>()<a class="reference internal" href="../_modules/django/http/request.html#HttpRequest.xreadlines"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpRequest.xreadlines" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="django.http.HttpRequest.__iter__"> <code class="descclassname">HttpRequest.</code><code class="descname">__iter__</code>()<a class="headerlink" href="#django.http.HttpRequest.__iter__" title="Permalink to this definition">¶</a></dt> <dd><p>Methods implementing a file-like interface for reading from an HttpRequest instance. This makes it possible to consume an incoming request in a streaming fashion. A common use-case would be to process a big XML payload with an iterative parser without constructing a whole XML tree in memory.</p> <p>Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xml.etree.ElementTree</span> <span class="k">as</span> <span class="nn">ET</span> <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">ET</span><span class="o">.</span><span class="n">iterparse</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="n">process</span><span class="p">(</span><span class="n">element</span><span class="p">)</span> </pre></div> </div> </dd></dl> </div> </div> <div class="section" id="s-querydict-objects"> <span id="querydict-objects"></span><h2>QueryDict objects<a class="headerlink" href="#querydict-objects" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="django.http.QueryDict"> <em class="property">class </em><code class="descname">QueryDict</code><a class="reference internal" href="../_modules/django/http/request.html#QueryDict"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>In an <a class="reference internal" href="#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> object, the <code class="docutils literal"><span class="pre">GET</span></code> and <code class="docutils literal"><span class="pre">POST</span></code> attributes are instances of <code class="docutils literal"><span class="pre">django.http.QueryDict</span></code>, a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <code class="docutils literal"><span class="pre"><select</span> <span class="pre">multiple></span></code>, pass multiple values for the same key.</p> <p>The <code class="docutils literal"><span class="pre">QueryDict</span></code>s at <code class="docutils literal"><span class="pre">request.POST</span></code> and <code class="docutils literal"><span class="pre">request.GET</span></code> will be immutable when accessed in a normal request/response cycle. To get a mutable version you need to use <code class="docutils literal"><span class="pre">.copy()</span></code>.</p> <div class="section" id="s-id1"> <span id="id1"></span><h3>Methods<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h3> <p><a class="reference internal" href="#django.http.QueryDict" title="django.http.QueryDict"><code class="xref py py-class docutils literal"><span class="pre">QueryDict</span></code></a> implements all the standard dictionary methods because it’s a subclass of dictionary. Exceptions are outlined here:</p> <dl class="method"> <dt id="django.http.QueryDict.__init__"> <code class="descclassname">QueryDict.</code><code class="descname">__init__</code>(<em>query_string=None</em>, <em>mutable=False</em>, <em>encoding=None</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.__init__"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Instantiates a <code class="docutils literal"><span class="pre">QueryDict</span></code> object based on <code class="docutils literal"><span class="pre">query_string</span></code>.</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1&a=2&c=3'</span><span class="p">)</span> <span class="go"><QueryDict: {'a': ['1', '2'], 'c': ['3']}></span> </pre></div> </div> <p>If <code class="docutils literal"><span class="pre">query_string</span></code> is not passed in, the resulting <code class="docutils literal"><span class="pre">QueryDict</span></code> will be empty (it will have no keys or values).</p> <p>Most <code class="docutils literal"><span class="pre">QueryDict</span></code>s you encounter, and in particular those at <code class="docutils literal"><span class="pre">request.POST</span></code> and <code class="docutils literal"><span class="pre">request.GET</span></code>, will be immutable. If you are instantiating one yourself, you can make it mutable by passing <code class="docutils literal"><span class="pre">mutable=True</span></code> to its <code class="docutils literal"><span class="pre">__init__()</span></code>.</p> <p>Strings for setting both keys and values will be converted from <code class="docutils literal"><span class="pre">encoding</span></code> to unicode. If encoding is not set, it defaults to <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CHARSET</span></code></a>.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.8:</span> <p>In previous versions, <code class="docutils literal"><span class="pre">query_string</span></code> was a required positional argument.</p> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.__getitem__"> <code class="descclassname">QueryDict.</code><code class="descname">__getitem__</code>(<em>key</em>)<a class="headerlink" href="#django.http.QueryDict.__getitem__" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the value for the given key. If the key has more than one value, <code class="docutils literal"><span class="pre">__getitem__()</span></code> returns the last value. Raises <code class="docutils literal"><span class="pre">django.utils.datastructures.MultiValueDictKeyError</span></code> if the key does not exist. (This is a subclass of Python’s standard <code class="docutils literal"><span class="pre">KeyError</span></code>, so you can stick to catching <code class="docutils literal"><span class="pre">KeyError</span></code>.)</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.__setitem__"> <code class="descclassname">QueryDict.</code><code class="descname">__setitem__</code>(<em>key</em>, <em>value</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.__setitem__"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.__setitem__" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the given key to <code class="docutils literal"><span class="pre">[value]</span></code> (a Python list whose single element is <code class="docutils literal"><span class="pre">value</span></code>). Note that this, as other dictionary functions that have side effects, can only be called on a mutable <code class="docutils literal"><span class="pre">QueryDict</span></code> (such as one that was created via <code class="docutils literal"><span class="pre">copy()</span></code>).</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.__contains__"> <code class="descclassname">QueryDict.</code><code class="descname">__contains__</code>(<em>key</em>)<a class="headerlink" href="#django.http.QueryDict.__contains__" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal"><span class="pre">True</span></code> if the given key is set. This lets you do, e.g., <code class="docutils literal"><span class="pre">if</span> <span class="pre">"foo"</span> <span class="pre">in</span> <span class="pre">request.GET</span></code>.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.get"> <code class="descclassname">QueryDict.</code><code class="descname">get</code>(<em>key</em>, <em>default=None</em>)<a class="headerlink" href="#django.http.QueryDict.get" title="Permalink to this definition">¶</a></dt> <dd><p>Uses the same logic as <code class="docutils literal"><span class="pre">__getitem__()</span></code> above, with a hook for returning a default value if the key doesn’t exist.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.setdefault"> <code class="descclassname">QueryDict.</code><code class="descname">setdefault</code>(<em>key</em>, <em>default=None</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.setdefault"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.setdefault" title="Permalink to this definition">¶</a></dt> <dd><p>Just like the standard dictionary <code class="docutils literal"><span class="pre">setdefault()</span></code> method, except it uses <code class="docutils literal"><span class="pre">__setitem__()</span></code> internally.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.update"> <code class="descclassname">QueryDict.</code><code class="descname">update</code>(<em>other_dict</em>)<a class="headerlink" href="#django.http.QueryDict.update" title="Permalink to this definition">¶</a></dt> <dd><p>Takes either a <code class="docutils literal"><span class="pre">QueryDict</span></code> or standard dictionary. Just like the standard dictionary <code class="docutils literal"><span class="pre">update()</span></code> method, except it <em>appends</em> to the current dictionary items rather than replacing them. For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1'</span><span class="p">,</span> <span class="n">mutable</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s1">'a'</span><span class="p">:</span> <span class="s1">'2'</span><span class="p">})</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">getlist</span><span class="p">(</span><span class="s1">'a'</span><span class="p">)</span> <span class="go">['1', '2']</span> <span class="gp">>>> </span><span class="n">q</span><span class="p">[</span><span class="s1">'a'</span><span class="p">]</span> <span class="c1"># returns the last</span> <span class="go">'2'</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.items"> <code class="descclassname">QueryDict.</code><code class="descname">items</code>()<a class="headerlink" href="#django.http.QueryDict.items" title="Permalink to this definition">¶</a></dt> <dd><p>Just like the standard dictionary <code class="docutils literal"><span class="pre">items()</span></code> method, except this uses the same last-value logic as <code class="docutils literal"><span class="pre">__getitem__()</span></code>. For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1&a=2&a=3'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="go">[('a', '3')]</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.iteritems"> <code class="descclassname">QueryDict.</code><code class="descname">iteritems</code>()<a class="headerlink" href="#django.http.QueryDict.iteritems" title="Permalink to this definition">¶</a></dt> <dd><p>Just like the standard dictionary <code class="docutils literal"><span class="pre">iteritems()</span></code> method. Like <a class="reference internal" href="#django.http.QueryDict.items" title="django.http.QueryDict.items"><code class="xref py py-meth docutils literal"><span class="pre">QueryDict.items()</span></code></a> this uses the same last-value logic as <a class="reference internal" href="#django.http.QueryDict.__getitem__" title="django.http.QueryDict.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">QueryDict.__getitem__()</span></code></a>.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.iterlists"> <code class="descclassname">QueryDict.</code><code class="descname">iterlists</code>()<a class="headerlink" href="#django.http.QueryDict.iterlists" title="Permalink to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#django.http.QueryDict.iteritems" title="django.http.QueryDict.iteritems"><code class="xref py py-meth docutils literal"><span class="pre">QueryDict.iteritems()</span></code></a> except it includes all values, as a list, for each member of the dictionary.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.values"> <code class="descclassname">QueryDict.</code><code class="descname">values</code>()<a class="headerlink" href="#django.http.QueryDict.values" title="Permalink to this definition">¶</a></dt> <dd><p>Just like the standard dictionary <code class="docutils literal"><span class="pre">values()</span></code> method, except this uses the same last-value logic as <code class="docutils literal"><span class="pre">__getitem__()</span></code>. For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1&a=2&a=3'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">values</span><span class="p">()</span> <span class="go">['3']</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.itervalues"> <code class="descclassname">QueryDict.</code><code class="descname">itervalues</code>()<a class="headerlink" href="#django.http.QueryDict.itervalues" title="Permalink to this definition">¶</a></dt> <dd><p>Just like <a class="reference internal" href="#django.http.QueryDict.values" title="django.http.QueryDict.values"><code class="xref py py-meth docutils literal"><span class="pre">QueryDict.values()</span></code></a>, except an iterator.</p> </dd></dl> <p>In addition, <code class="docutils literal"><span class="pre">QueryDict</span></code> has the following methods:</p> <dl class="method"> <dt id="django.http.QueryDict.copy"> <code class="descclassname">QueryDict.</code><code class="descname">copy</code>()<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.copy"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.copy" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a copy of the object, using <code class="docutils literal"><span class="pre">copy.deepcopy()</span></code> from the Python standard library. This copy will be mutable even if the original was not.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.getlist"> <code class="descclassname">QueryDict.</code><code class="descname">getlist</code>(<em>key</em>, <em>default=None</em>)<a class="headerlink" href="#django.http.QueryDict.getlist" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn’t exist and no default value was provided. It’s guaranteed to return a list of some sort unless the default value provided is not a list.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.setlist"> <code class="descclassname">QueryDict.</code><code class="descname">setlist</code>(<em>key</em>, <em>list_</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.setlist"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.setlist" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the given key to <code class="docutils literal"><span class="pre">list_</span></code> (unlike <code class="docutils literal"><span class="pre">__setitem__()</span></code>).</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.appendlist"> <code class="descclassname">QueryDict.</code><code class="descname">appendlist</code>(<em>key</em>, <em>item</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.appendlist"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.appendlist" title="Permalink to this definition">¶</a></dt> <dd><p>Appends an item to the internal list associated with key.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.setlistdefault"> <code class="descclassname">QueryDict.</code><code class="descname">setlistdefault</code>(<em>key</em>, <em>default_list=None</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.setlistdefault"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.setlistdefault" title="Permalink to this definition">¶</a></dt> <dd><p>Just like <code class="docutils literal"><span class="pre">setdefault</span></code>, except it takes a list of values instead of a single value.</p> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.lists"> <code class="descclassname">QueryDict.</code><code class="descname">lists</code>()<a class="headerlink" href="#django.http.QueryDict.lists" title="Permalink to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#django.http.QueryDict.items" title="django.http.QueryDict.items"><code class="xref py py-meth docutils literal"><span class="pre">items()</span></code></a>, except it includes all values, as a list, for each member of the dictionary. For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1&a=2&a=3'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">lists</span><span class="p">()</span> <span class="go">[('a', ['1', '2', '3'])]</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.pop"> <code class="descclassname">QueryDict.</code><code class="descname">pop</code>(<em>key</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.pop"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.pop" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a list of values for the given key and removes them from the dictionary. Raises <code class="docutils literal"><span class="pre">KeyError</span></code> if the key does not exist. For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1&a=2&a=3'</span><span class="p">,</span> <span class="n">mutable</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">'a'</span><span class="p">)</span> <span class="go">['1', '2', '3']</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.popitem"> <code class="descclassname">QueryDict.</code><code class="descname">popitem</code>()<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.popitem"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.popitem" title="Permalink to this definition">¶</a></dt> <dd><p>Removes an arbitrary member of the dictionary (since there’s no concept of ordering), and returns a two value tuple containing the key and a list of all values for the key. Raises <code class="docutils literal"><span class="pre">KeyError</span></code> when called on an empty dictionary. For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1&a=2&a=3'</span><span class="p">,</span> <span class="n">mutable</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">popitem</span><span class="p">()</span> <span class="go">('a', ['1', '2', '3'])</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.dict"> <code class="descclassname">QueryDict.</code><code class="descname">dict</code>()<a class="headerlink" href="#django.http.QueryDict.dict" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal"><span class="pre">dict</span></code> representation of <code class="docutils literal"><span class="pre">QueryDict</span></code>. For every (key, list) pair in <code class="docutils literal"><span class="pre">QueryDict</span></code>, <code class="docutils literal"><span class="pre">dict</span></code> will have (key, item), where item is one element of the list, using same logic as <a class="reference internal" href="#django.http.QueryDict.__getitem__" title="django.http.QueryDict.__getitem__"><code class="xref py py-meth docutils literal"><span class="pre">QueryDict.__getitem__()</span></code></a>:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=1&a=3&a=5'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">dict</span><span class="p">()</span> <span class="go">{'a': '5'}</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.http.QueryDict.urlencode"> <code class="descclassname">QueryDict.</code><code class="descname">urlencode</code>(<em>safe=None</em>)<a class="reference internal" href="../_modules/django/http/request.html#QueryDict.urlencode"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.QueryDict.urlencode" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a string of the data in query-string format. Example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="s1">'a=2&b=3&b=5'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">urlencode</span><span class="p">()</span> <span class="go">'a=2&b=3&b=5'</span> </pre></div> </div> <p>Optionally, urlencode can be passed characters which do not require encoding. For example:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span> <span class="o">=</span> <span class="n">QueryDict</span><span class="p">(</span><span class="n">mutable</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">q</span><span class="p">[</span><span class="s1">'next'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'/a&b/'</span> <span class="gp">>>> </span><span class="n">q</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="n">safe</span><span class="o">=</span><span class="s1">'/'</span><span class="p">)</span> <span class="go">'next=/a%26b/'</span> </pre></div> </div> </dd></dl> </div> </div> <div class="section" id="s-httpresponse-objects"> <span id="httpresponse-objects"></span><h2>HttpResponse objects<a class="headerlink" href="#httpresponse-objects" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="django.http.HttpResponse"> <em class="property">class </em><code class="descname">HttpResponse</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponse"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponse" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>In contrast to <a class="reference internal" href="#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> objects, which are created automatically by Django, <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> objects are your responsibility. Each view you write is responsible for instantiating, populating and returning an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>.</p> <p>The <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> class lives in the <a class="reference internal" href="#module-django.http" title="django.http: Classes dealing with HTTP requests and responses."><code class="xref py py-mod docutils literal"><span class="pre">django.http</span></code></a> module.</p> <div class="section" id="s-usage"> <span id="usage"></span><h3>Usage<a class="headerlink" href="#usage" title="Permalink to this headline">¶</a></h3> <div class="section" id="s-passing-strings"> <span id="passing-strings"></span><h4>Passing strings<a class="headerlink" href="#passing-strings" title="Permalink to this headline">¶</a></h4> <p>Typical usage is to pass the contents of the page, as a string, to the <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> constructor:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.http</span> <span class="k">import</span> <span class="n">HttpResponse</span> <span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">"Here's the text of the Web page."</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">"Text only, please."</span><span class="p">,</span> <span class="n">content_type</span><span class="o">=</span><span class="s2">"text/plain"</span><span class="p">)</span> </pre></div> </div> <p>But if you want to add content incrementally, you can use <code class="docutils literal"><span class="pre">response</span></code> as a file-like object:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">response</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"<p>Here's the text of the Web page.</p>"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">response</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"<p>Here's another paragraph.</p>"</span><span class="p">)</span> </pre></div> </div> </div> <div class="section" id="s-passing-iterators"> <span id="passing-iterators"></span><h4>Passing iterators<a class="headerlink" href="#passing-iterators" title="Permalink to this headline">¶</a></h4> <p>Finally, you can pass <code class="docutils literal"><span class="pre">HttpResponse</span></code> an iterator rather than strings. <code class="docutils literal"><span class="pre">HttpResponse</span></code> will consume the iterator immediately, store its content as a string, and discard it.</p> <p>If you need the response to be streamed from the iterator to the client, you must use the <a class="reference internal" href="#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> class instead.</p> </div> <div class="section" id="s-setting-header-fields"> <span id="setting-header-fields"></span><h4>Setting header fields<a class="headerlink" href="#setting-header-fields" title="Permalink to this headline">¶</a></h4> <p>To set or remove a header field in your response, treat it like a dictionary:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">response</span><span class="p">[</span><span class="s1">'Age'</span><span class="p">]</span> <span class="o">=</span> <span class="mi">120</span> <span class="gp">>>> </span><span class="k">del</span> <span class="n">response</span><span class="p">[</span><span class="s1">'Age'</span><span class="p">]</span> </pre></div> </div> <p>Note that unlike a dictionary, <code class="docutils literal"><span class="pre">del</span></code> doesn’t raise <code class="docutils literal"><span class="pre">KeyError</span></code> if the header field doesn’t exist.</p> <p>For setting the <code class="docutils literal"><span class="pre">Cache-Control</span></code> and <code class="docutils literal"><span class="pre">Vary</span></code> header fields, it is recommended to use the <a class="reference internal" href="utils.html#django.utils.cache.patch_cache_control" title="django.utils.cache.patch_cache_control"><code class="xref py py-func docutils literal"><span class="pre">patch_cache_control()</span></code></a> and <a class="reference internal" href="utils.html#django.utils.cache.patch_vary_headers" title="django.utils.cache.patch_vary_headers"><code class="xref py py-func docutils literal"><span class="pre">patch_vary_headers()</span></code></a> methods from <a class="reference internal" href="utils.html#module-django.utils.cache" title="django.utils.cache: Helper functions for controlling caching."><code class="xref py py-mod docutils literal"><span class="pre">django.utils.cache</span></code></a>, since these fields can have multiple, comma-separated values. The “patch” methods ensure that other values, e.g. added by a middleware, are not removed.</p> <p>HTTP header fields cannot contain newlines. An attempt to set a header field containing a newline character (CR or LF) will raise <code class="docutils literal"><span class="pre">BadHeaderError</span></code></p> </div> <div class="section" id="s-telling-the-browser-to-treat-the-response-as-a-file-attachment"> <span id="telling-the-browser-to-treat-the-response-as-a-file-attachment"></span><h4>Telling the browser to treat the response as a file attachment<a class="headerlink" href="#telling-the-browser-to-treat-the-response-as-a-file-attachment" title="Permalink to this headline">¶</a></h4> <p>To tell the browser to treat the response as a file attachment, use the <code class="docutils literal"><span class="pre">content_type</span></code> argument and set the <code class="docutils literal"><span class="pre">Content-Disposition</span></code> header. For example, this is how you might return a Microsoft Excel spreadsheet:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="n">my_data</span><span class="p">,</span> <span class="n">content_type</span><span class="o">=</span><span class="s1">'application/vnd.ms-excel'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">response</span><span class="p">[</span><span class="s1">'Content-Disposition'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'attachment; filename="foo.xls"'</span> </pre></div> </div> <p>There’s nothing Django-specific about the <code class="docutils literal"><span class="pre">Content-Disposition</span></code> header, but it’s easy to forget the syntax, so we’ve included it here.</p> </div> </div> <div class="section" id="s-id2"> <span id="id2"></span><h3>Attributes<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h3> <dl class="attribute"> <dt id="django.http.HttpResponse.content"> <code class="descclassname">HttpResponse.</code><code class="descname">content</code><a class="headerlink" href="#django.http.HttpResponse.content" title="Permalink to this definition">¶</a></dt> <dd><p>A bytestring representing the content, encoded from a Unicode object if necessary.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpResponse.charset"> <code class="descclassname">HttpResponse.</code><code class="descname">charset</code><a class="headerlink" href="#django.http.HttpResponse.charset" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p>A string denoting the charset in which the response will be encoded. If not given at <code class="docutils literal"><span class="pre">HttpResponse</span></code> instantiation time, it will be extracted from <code class="docutils literal"><span class="pre">content_type</span></code> and if that is unsuccessful, the <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CHARSET</span></code></a> setting will be used.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpResponse.status_code"> <code class="descclassname">HttpResponse.</code><code class="descname">status_code</code><a class="headerlink" href="#django.http.HttpResponse.status_code" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10">HTTP status code</a> for the response.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpResponse.reason_phrase"> <code class="descclassname">HttpResponse.</code><code class="descname">reason_phrase</code><a class="headerlink" href="#django.http.HttpResponse.reason_phrase" title="Permalink to this definition">¶</a></dt> <dd><p>The HTTP reason phrase for the response.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpResponse.streaming"> <code class="descclassname">HttpResponse.</code><code class="descname">streaming</code><a class="headerlink" href="#django.http.HttpResponse.streaming" title="Permalink to this definition">¶</a></dt> <dd><p>This is always <code class="docutils literal"><span class="pre">False</span></code>.</p> <p>This attribute exists so middleware can treat streaming responses differently from regular responses.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.HttpResponse.closed"> <code class="descclassname">HttpResponse.</code><code class="descname">closed</code><a class="headerlink" href="#django.http.HttpResponse.closed" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p><code class="docutils literal"><span class="pre">True</span></code> if the response has been closed.</p> </dd></dl> </div> <div class="section" id="s-id3"> <span id="id3"></span><h3>Methods<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h3> <dl class="method"> <dt id="django.http.HttpResponse.__init__"> <code class="descclassname">HttpResponse.</code><code class="descname">__init__</code>(<em>content=''</em>, <em>content_type=None</em>, <em>status=200</em>, <em>reason=None</em>, <em>charset=None</em>)<a class="reference internal" href="../_modules/django/http/response.html#HttpResponse.__init__"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponse.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Instantiates an <code class="docutils literal"><span class="pre">HttpResponse</span></code> object with the given page content and content type.</p> <p><code class="docutils literal"><span class="pre">content</span></code> should be an iterator or a string. If it’s an iterator, it should return strings, and those strings will be joined together to form the content of the response. If it is not an iterator or a string, it will be converted to a string when accessed.</p> <p><code class="docutils literal"><span class="pre">content_type</span></code> is the MIME type optionally completed by a character set encoding and is used to fill the HTTP <code class="docutils literal"><span class="pre">Content-Type</span></code> header. If not specified, it is formed by the <a class="reference internal" href="settings.html#std:setting-DEFAULT_CONTENT_TYPE"><code class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CONTENT_TYPE</span></code></a> and <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CHARSET</span></code></a> settings, by default: “<cite>text/html; charset=utf-8</cite>”.</p> <p><code class="docutils literal"><span class="pre">status</span></code> is the <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10">HTTP status code</a> for the response.</p> <p><code class="docutils literal"><span class="pre">reason</span></code> is the HTTP response phrase. If not provided, a default phrase will be used.</p> <p><code class="docutils literal"><span class="pre">charset</span></code> is the charset in which the response will be encoded. If not given it will be extracted from <code class="docutils literal"><span class="pre">content_type</span></code>, and if that is unsuccessful, the <a class="reference internal" href="settings.html#std:setting-DEFAULT_CHARSET"><code class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CHARSET</span></code></a> setting will be used.</p> <div class="versionadded"> <span class="title">New in Django 1.8:</span> <p>The <code class="docutils literal"><span class="pre">charset</span></code> parameter was added.</p> </div> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.__setitem__"> <code class="descclassname">HttpResponse.</code><code class="descname">__setitem__</code>(<em>header</em>, <em>value</em>)<a class="headerlink" href="#django.http.HttpResponse.__setitem__" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the given header name to the given value. Both <code class="docutils literal"><span class="pre">header</span></code> and <code class="docutils literal"><span class="pre">value</span></code> should be strings.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.__delitem__"> <code class="descclassname">HttpResponse.</code><code class="descname">__delitem__</code>(<em>header</em>)<a class="headerlink" href="#django.http.HttpResponse.__delitem__" title="Permalink to this definition">¶</a></dt> <dd><p>Deletes the header with the given name. Fails silently if the header doesn’t exist. Case-insensitive.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.__getitem__"> <code class="descclassname">HttpResponse.</code><code class="descname">__getitem__</code>(<em>header</em>)<a class="headerlink" href="#django.http.HttpResponse.__getitem__" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the value for the given header name. Case-insensitive.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.has_header"> <code class="descclassname">HttpResponse.</code><code class="descname">has_header</code>(<em>header</em>)<a class="headerlink" href="#django.http.HttpResponse.has_header" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal"><span class="pre">True</span></code> or <code class="docutils literal"><span class="pre">False</span></code> based on a case-insensitive check for a header with the given name.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.setdefault"> <code class="descclassname">HttpResponse.</code><code class="descname">setdefault</code>(<em>header</em>, <em>value</em>)<a class="headerlink" href="#django.http.HttpResponse.setdefault" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p>Sets a header unless it has already been set.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.set_cookie"> <code class="descclassname">HttpResponse.</code><code class="descname">set_cookie</code>(<em>key</em>, <em>value=''</em>, <em>max_age=None</em>, <em>expires=None</em>, <em>path='/'</em>, <em>domain=None</em>, <em>secure=None</em>, <em>httponly=False</em>)<a class="headerlink" href="#django.http.HttpResponse.set_cookie" title="Permalink to this definition">¶</a></dt> <dd><p>Sets a cookie. The parameters are the same as in the <code class="xref py py-class docutils literal"><span class="pre">Morsel</span></code> cookie object in the Python standard library.</p> <ul> <li><p class="first"><code class="docutils literal"><span class="pre">max_age</span></code> should be a number of seconds, or <code class="docutils literal"><span class="pre">None</span></code> (default) if the cookie should last only as long as the client’s browser session. If <code class="docutils literal"><span class="pre">expires</span></code> is not specified, it will be calculated.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">expires</span></code> should either be a string in the format <code class="docutils literal"><span class="pre">"Wdy,</span> <span class="pre">DD-Mon-YY</span> <span class="pre">HH:MM:SS</span> <span class="pre">GMT"</span></code> or a <code class="docutils literal"><span class="pre">datetime.datetime</span></code> object in UTC. If <code class="docutils literal"><span class="pre">expires</span></code> is a <code class="docutils literal"><span class="pre">datetime</span></code> object, the <code class="docutils literal"><span class="pre">max_age</span></code> will be calculated.</p> </li> <li><p class="first">Use <code class="docutils literal"><span class="pre">domain</span></code> if you want to set a cross-domain cookie. For example, <code class="docutils literal"><span class="pre">domain=".lawrence.com"</span></code> will set a cookie that is readable by the domains www.lawrence.com, blogs.lawrence.com and calendars.lawrence.com. Otherwise, a cookie will only be readable by the domain that set it.</p> </li> <li><p class="first">Use <code class="docutils literal"><span class="pre">httponly=True</span></code> if you want to prevent client-side JavaScript from having access to the cookie.</p> <p><a class="reference external" href="https://www.owasp.org/index.php/HTTPOnly">HTTPOnly</a> is a flag included in a Set-Cookie HTTP response header. It is not part of the <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> standard for cookies, and it isn’t honored consistently by all browsers. However, when it is honored, it can be a useful way to mitigate the risk of a client-side script from accessing the protected cookie data.</p> </li> </ul> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">Both <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> and <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc6265.html"><strong>RFC 6265</strong></a> state that user agents should support cookies of at least 4096 bytes. For many browsers this is also the maximum size. Django will not raise an exception if there’s an attempt to store a cookie of more than 4096 bytes, but many browsers will not set the cookie correctly.</p> </div> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.set_signed_cookie"> <code class="descclassname">HttpResponse.</code><code class="descname">set_signed_cookie</code>(<em>key</em>, <em>value</em>, <em>salt=''</em>, <em>max_age=None</em>, <em>expires=None</em>, <em>path='/'</em>, <em>domain=None</em>, <em>secure=None</em>, <em>httponly=True</em>)<a class="headerlink" href="#django.http.HttpResponse.set_signed_cookie" title="Permalink to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#django.http.HttpResponse.set_cookie" title="django.http.HttpResponse.set_cookie"><code class="xref py py-meth docutils literal"><span class="pre">set_cookie()</span></code></a>, but <a class="reference internal" href="../topics/signing.html"><span class="doc">cryptographic signing</span></a> the cookie before setting it. Use in conjunction with <a class="reference internal" href="#django.http.HttpRequest.get_signed_cookie" title="django.http.HttpRequest.get_signed_cookie"><code class="xref py py-meth docutils literal"><span class="pre">HttpRequest.get_signed_cookie()</span></code></a>. You can use the optional <code class="docutils literal"><span class="pre">salt</span></code> argument for added key strength, but you will need to remember to pass it to the corresponding <a class="reference internal" href="#django.http.HttpRequest.get_signed_cookie" title="django.http.HttpRequest.get_signed_cookie"><code class="xref py py-meth docutils literal"><span class="pre">HttpRequest.get_signed_cookie()</span></code></a> call.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.delete_cookie"> <code class="descclassname">HttpResponse.</code><code class="descname">delete_cookie</code>(<em>key</em>, <em>path='/'</em>, <em>domain=None</em>)<a class="headerlink" href="#django.http.HttpResponse.delete_cookie" title="Permalink to this definition">¶</a></dt> <dd><p>Deletes the cookie with the given key. Fails silently if the key doesn’t exist.</p> <p>Due to the way cookies work, <code class="docutils literal"><span class="pre">path</span></code> and <code class="docutils literal"><span class="pre">domain</span></code> should be the same values you used in <code class="docutils literal"><span class="pre">set_cookie()</span></code> – otherwise the cookie may not be deleted.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.write"> <code class="descclassname">HttpResponse.</code><code class="descname">write</code>(<em>content</em>)<a class="reference internal" href="../_modules/django/http/response.html#HttpResponse.write"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponse.write" title="Permalink to this definition">¶</a></dt> <dd><p>This method makes an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> instance a file-like object.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.flush"> <code class="descclassname">HttpResponse.</code><code class="descname">flush</code>()<a class="headerlink" href="#django.http.HttpResponse.flush" title="Permalink to this definition">¶</a></dt> <dd><p>This method makes an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> instance a file-like object.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.tell"> <code class="descclassname">HttpResponse.</code><code class="descname">tell</code>()<a class="reference internal" href="../_modules/django/http/response.html#HttpResponse.tell"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponse.tell" title="Permalink to this definition">¶</a></dt> <dd><p>This method makes an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> instance a file-like object.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.getvalue"> <code class="descclassname">HttpResponse.</code><code class="descname">getvalue</code>()<a class="reference internal" href="../_modules/django/http/response.html#HttpResponse.getvalue"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponse.getvalue" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p>Returns the value of <a class="reference internal" href="#django.http.HttpResponse.content" title="django.http.HttpResponse.content"><code class="xref py py-attr docutils literal"><span class="pre">HttpResponse.content</span></code></a>. This method makes an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> instance a stream-like object.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.writable"> <code class="descclassname">HttpResponse.</code><code class="descname">writable</code>()<a class="reference internal" href="../_modules/django/http/response.html#HttpResponse.writable"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponse.writable" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p>Always <code class="docutils literal"><span class="pre">True</span></code>. This method makes an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> instance a stream-like object.</p> </dd></dl> <dl class="method"> <dt id="django.http.HttpResponse.writelines"> <code class="descclassname">HttpResponse.</code><code class="descname">writelines</code>(<em>lines</em>)<a class="reference internal" href="../_modules/django/http/response.html#HttpResponse.writelines"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponse.writelines" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p>Writes a list of lines to the response. Line separators are not added. This method makes an <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> instance a stream-like object.</p> </dd></dl> </div> <div class="section" id="s-httpresponse-subclasses"> <span id="s-ref-httpresponse-subclasses"></span><span id="httpresponse-subclasses"></span><span id="ref-httpresponse-subclasses"></span><h3>HttpResponse subclasses<a class="headerlink" href="#httpresponse-subclasses" title="Permalink to this headline">¶</a></h3> <p>Django includes a number of <code class="docutils literal"><span class="pre">HttpResponse</span></code> subclasses that handle different types of HTTP responses. Like <code class="docutils literal"><span class="pre">HttpResponse</span></code>, these subclasses live in <a class="reference internal" href="#module-django.http" title="django.http: Classes dealing with HTTP requests and responses."><code class="xref py py-mod docutils literal"><span class="pre">django.http</span></code></a>.</p> <dl class="class"> <dt id="django.http.HttpResponseRedirect"> <em class="property">class </em><code class="descname">HttpResponseRedirect</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseRedirect"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseRedirect" title="Permalink to this definition">¶</a></dt> <dd><p>The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. <code class="docutils literal"><span class="pre">'http://www.yahoo.com/search/'</span></code>) or an absolute path with no domain (e.g. <code class="docutils literal"><span class="pre">'/search/'</span></code>). See <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> for other optional constructor arguments. Note that this returns an HTTP status code 302.</p> <dl class="attribute"> <dt id="django.http.HttpResponseRedirect.url"> <code class="descname">url</code><a class="headerlink" href="#django.http.HttpResponseRedirect.url" title="Permalink to this definition">¶</a></dt> <dd><p>This read-only attribute represents the URL the response will redirect to (equivalent to the <code class="docutils literal"><span class="pre">Location</span></code> response header).</p> </dd></dl> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponsePermanentRedirect"> <em class="property">class </em><code class="descname">HttpResponsePermanentRedirect</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponsePermanentRedirect"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponsePermanentRedirect" title="Permalink to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal"><span class="pre">HttpResponseRedirect</span></code></a>, but it returns a permanent redirect (HTTP status code 301) instead of a “found” redirect (status code 302).</p> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponseNotModified"> <em class="property">class </em><code class="descname">HttpResponseNotModified</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseNotModified"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseNotModified" title="Permalink to this definition">¶</a></dt> <dd><p>The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304).</p> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponseBadRequest"> <em class="property">class </em><code class="descname">HttpResponseBadRequest</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseBadRequest"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseBadRequest" title="Permalink to this definition">¶</a></dt> <dd><p>Acts just like <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> but uses a 400 status code.</p> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponseNotFound"> <em class="property">class </em><code class="descname">HttpResponseNotFound</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseNotFound"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseNotFound" title="Permalink to this definition">¶</a></dt> <dd><p>Acts just like <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> but uses a 404 status code.</p> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponseForbidden"> <em class="property">class </em><code class="descname">HttpResponseForbidden</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseForbidden"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseForbidden" title="Permalink to this definition">¶</a></dt> <dd><p>Acts just like <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> but uses a 403 status code.</p> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponseNotAllowed"> <em class="property">class </em><code class="descname">HttpResponseNotAllowed</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseNotAllowed"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseNotAllowed" title="Permalink to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>, but uses a 405 status code. The first argument to the constructor is required: a list of permitted methods (e.g. <code class="docutils literal"><span class="pre">['GET',</span> <span class="pre">'POST']</span></code>).</p> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponseGone"> <em class="property">class </em><code class="descname">HttpResponseGone</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseGone"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseGone" title="Permalink to this definition">¶</a></dt> <dd><p>Acts just like <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> but uses a 410 status code.</p> </dd></dl> <dl class="class"> <dt id="django.http.HttpResponseServerError"> <em class="property">class </em><code class="descname">HttpResponseServerError</code><a class="reference internal" href="../_modules/django/http/response.html#HttpResponseServerError"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.HttpResponseServerError" title="Permalink to this definition">¶</a></dt> <dd><p>Acts just like <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> but uses a 500 status code.</p> </dd></dl> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">If a custom subclass of <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> implements a <code class="docutils literal"><span class="pre">render</span></code> method, Django will treat it as emulating a <a class="reference internal" href="template-response.html#django.template.response.SimpleTemplateResponse" title="django.template.response.SimpleTemplateResponse"><code class="xref py py-class docutils literal"><span class="pre">SimpleTemplateResponse</span></code></a>, and the <code class="docutils literal"><span class="pre">render</span></code> method must itself return a valid response object.</p> </div> </div> </div> <div class="section" id="s-jsonresponse-objects"> <span id="jsonresponse-objects"></span><h2>JsonResponse objects<a class="headerlink" href="#jsonresponse-objects" title="Permalink to this headline">¶</a></h2> <div class="versionadded"> <span class="title">New in Django 1.7.</span> </div> <dl class="class"> <dt id="django.http.JsonResponse"> <em class="property">class </em><code class="descname">JsonResponse</code>(<em>data</em>, <em>encoder=DjangoJSONEncoder</em>, <em>safe=True</em>, <em>**kwargs</em>)<a class="reference internal" href="../_modules/django/http/response.html#JsonResponse"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.JsonResponse" title="Permalink to this definition">¶</a></dt> <dd><p>An <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences:</p> <p>Its default <code class="docutils literal"><span class="pre">Content-Type</span></code> header is set to <code class="docutils literal"><span class="pre">application/json</span></code>.</p> <p>The first parameter, <code class="docutils literal"><span class="pre">data</span></code>, should be a <code class="docutils literal"><span class="pre">dict</span></code> instance. If the <code class="docutils literal"><span class="pre">safe</span></code> parameter is set to <code class="docutils literal"><span class="pre">False</span></code> (see below) it can be any JSON-serializable object.</p> <p>The <code class="docutils literal"><span class="pre">encoder</span></code>, which defaults to <code class="docutils literal"><span class="pre">django.core.serializers.json.DjangoJSONEncoder</span></code>, will be used to serialize the data. See <a class="reference internal" href="../topics/serialization.html#serialization-formats-json"><span class="std std-ref">JSON serialization</span></a> for more details about this serializer.</p> <p>The <code class="docutils literal"><span class="pre">safe</span></code> boolean parameter defaults to <code class="docutils literal"><span class="pre">True</span></code>. If it’s set to <code class="docutils literal"><span class="pre">False</span></code>, any object can be passed for serialization (otherwise only <code class="docutils literal"><span class="pre">dict</span></code> instances are allowed). If <code class="docutils literal"><span class="pre">safe</span></code> is <code class="docutils literal"><span class="pre">True</span></code> and a non-<code class="docutils literal"><span class="pre">dict</span></code> object is passed as the first argument, a <code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code> will be raised.</p> </dd></dl> <div class="section" id="s-id4"> <span id="id4"></span><h3>Usage<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h3> <p>Typical usage could look like:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.http</span> <span class="k">import</span> <span class="n">JsonResponse</span> <span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">JsonResponse</span><span class="p">({</span><span class="s1">'foo'</span><span class="p">:</span> <span class="s1">'bar'</span><span class="p">})</span> <span class="gp">>>> </span><span class="n">response</span><span class="o">.</span><span class="n">content</span> <span class="go">b'{"foo": "bar"}'</span> </pre></div> </div> <div class="section" id="s-serializing-non-dictionary-objects"> <span id="serializing-non-dictionary-objects"></span><h4>Serializing non-dictionary objects<a class="headerlink" href="#serializing-non-dictionary-objects" title="Permalink to this headline">¶</a></h4> <p>In order to serialize objects other than <code class="docutils literal"><span class="pre">dict</span></code> you must set the <code class="docutils literal"><span class="pre">safe</span></code> parameter to <code class="docutils literal"><span class="pre">False</span></code>:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">JsonResponse</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="n">safe</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> </pre></div> </div> <p>Without passing <code class="docutils literal"><span class="pre">safe=False</span></code>, a <code class="xref py py-exc docutils literal"><span class="pre">TypeError</span></code> will be raised.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">Before the <a class="reference external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">5th edition of EcmaScript</a> it was possible to poison the JavaScript <code class="docutils literal"><span class="pre">Array</span></code> constructor. For this reason, Django does not allow passing non-dict objects to the <a class="reference internal" href="#django.http.JsonResponse" title="django.http.JsonResponse"><code class="xref py py-class docutils literal"><span class="pre">JsonResponse</span></code></a> constructor by default. However, most modern browsers implement EcmaScript 5 which removes this attack vector. Therefore it is possible to disable this security precaution.</p> </div> </div> <div class="section" id="s-changing-the-default-json-encoder"> <span id="changing-the-default-json-encoder"></span><h4>Changing the default JSON encoder<a class="headerlink" href="#changing-the-default-json-encoder" title="Permalink to this headline">¶</a></h4> <p>If you need to use a different JSON encoder class you can pass the <code class="docutils literal"><span class="pre">encoder</span></code> parameter to the constructor method:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">JsonResponse</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">encoder</span><span class="o">=</span><span class="n">MyJSONEncoder</span><span class="p">)</span> </pre></div> </div> </div> </div> </div> <div class="section" id="s-streaminghttpresponse-objects"> <span id="s-httpresponse-streaming"></span><span id="streaminghttpresponse-objects"></span><span id="httpresponse-streaming"></span><h2>StreamingHttpResponse objects<a class="headerlink" href="#streaminghttpresponse-objects" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="django.http.StreamingHttpResponse"> <em class="property">class </em><code class="descname">StreamingHttpResponse</code><a class="reference internal" href="../_modules/django/http/response.html#StreamingHttpResponse"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.StreamingHttpResponse" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>The <a class="reference internal" href="#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> class is used to stream a response from Django to the browser. You might want to do this if generating the response takes too long or uses too much memory. For instance, it’s useful for <a class="reference internal" href="../howto/outputting-csv.html#streaming-csv-files"><span class="std std-ref">generating large CSV files</span></a>.</p> <div class="admonition-performance-considerations admonition"> <p class="first admonition-title">Performance considerations</p> <p>Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance.</p> <p class="last">Generally speaking, you should perform expensive tasks outside of the request-response cycle, rather than resorting to a streamed response.</p> </div> <p>The <a class="reference internal" href="#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> is not a subclass of <a class="reference internal" href="#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>, because it features a slightly different API. However, it is almost identical, with the following notable differences:</p> <ul class="simple"> <li>It should be given an iterator that yields strings as content.</li> <li>You cannot access its content, except by iterating the response object itself. This should only occur when the response is returned to the client.</li> <li>It has no <code class="docutils literal"><span class="pre">content</span></code> attribute. Instead, it has a <a class="reference internal" href="#django.http.StreamingHttpResponse.streaming_content" title="django.http.StreamingHttpResponse.streaming_content"><code class="xref py py-attr docutils literal"><span class="pre">streaming_content</span></code></a> attribute.</li> <li>You cannot use the file-like object <code class="docutils literal"><span class="pre">tell()</span></code> or <code class="docutils literal"><span class="pre">write()</span></code> methods. Doing so will raise an exception.</li> </ul> <p><a class="reference internal" href="#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> should only be used in situations where it is absolutely required that the whole content isn’t iterated before transferring the data to the client. Because the content can’t be accessed, many middlewares can’t function normally. For example the <code class="docutils literal"><span class="pre">ETag</span></code> and <code class="docutils literal"><span class="pre">Content-</span> <span class="pre">Length</span></code> headers can’t be generated for streaming responses.</p> <div class="section" id="s-id5"> <span id="id5"></span><h3>Attributes<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h3> <dl class="attribute"> <dt id="django.http.StreamingHttpResponse.streaming_content"> <code class="descclassname">StreamingHttpResponse.</code><code class="descname">streaming_content</code><a class="headerlink" href="#django.http.StreamingHttpResponse.streaming_content" title="Permalink to this definition">¶</a></dt> <dd><p>An iterator of strings representing the content.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.StreamingHttpResponse.status_code"> <code class="descclassname">StreamingHttpResponse.</code><code class="descname">status_code</code><a class="headerlink" href="#django.http.StreamingHttpResponse.status_code" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10">HTTP status code</a> for the response.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.StreamingHttpResponse.reason_phrase"> <code class="descclassname">StreamingHttpResponse.</code><code class="descname">reason_phrase</code><a class="headerlink" href="#django.http.StreamingHttpResponse.reason_phrase" title="Permalink to this definition">¶</a></dt> <dd><p>The HTTP reason phrase for the response.</p> </dd></dl> <dl class="attribute"> <dt id="django.http.StreamingHttpResponse.streaming"> <code class="descclassname">StreamingHttpResponse.</code><code class="descname">streaming</code><a class="headerlink" href="#django.http.StreamingHttpResponse.streaming" title="Permalink to this definition">¶</a></dt> <dd><p>This is always <code class="docutils literal"><span class="pre">True</span></code>.</p> </dd></dl> </div> </div> <div class="section" id="s-fileresponse-objects"> <span id="fileresponse-objects"></span><h2>FileResponse objects<a class="headerlink" href="#fileresponse-objects" title="Permalink to this headline">¶</a></h2> <div class="versionadded"> <span class="title">New in Django 1.7.4.</span> </div> <dl class="class"> <dt id="django.http.FileResponse"> <em class="property">class </em><code class="descname">FileResponse</code><a class="reference internal" href="../_modules/django/http/response.html#FileResponse"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.http.FileResponse" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><a class="reference internal" href="#django.http.FileResponse" title="django.http.FileResponse"><code class="xref py py-class docutils literal"><span class="pre">FileResponse</span></code></a> is a subclass of <a class="reference internal" href="#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal"><span class="pre">StreamingHttpResponse</span></code></a> optimized for binary files. It uses <a class="reference external" href="https://www.python.org/dev/peps/pep-3333/#optional-platform-specific-file-handling">wsgi.file_wrapper</a> if provided by the wsgi server, otherwise it streams the file out in small chunks.</p> <p><code class="docutils literal"><span class="pre">FileResponse</span></code> expects a file open in binary mode like so:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.http</span> <span class="k">import</span> <span class="n">FileResponse</span> <span class="gp">>>> </span><span class="n">response</span> <span class="o">=</span> <span class="n">FileResponse</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s1">'myfile.png'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">))</span> </pre></div> </div> </div> </div> </div> </div> </div> <div class="yui-b" id="sidebar"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Request and response objects</a><ul> <li><a class="reference internal" href="#quick-overview">Quick overview</a></li> <li><a class="reference internal" href="#httprequest-objects">HttpRequest objects</a><ul> <li><a class="reference internal" href="#attributes">Attributes</a></li> <li><a class="reference internal" href="#attributes-set-by-middleware">Attributes set by middleware</a></li> <li><a class="reference internal" href="#methods">Methods</a></li> </ul> </li> <li><a class="reference internal" href="#querydict-objects">QueryDict objects</a><ul> <li><a class="reference internal" href="#id1">Methods</a></li> </ul> </li> <li><a class="reference internal" href="#httpresponse-objects">HttpResponse objects</a><ul> <li><a class="reference internal" href="#usage">Usage</a><ul> <li><a class="reference internal" href="#passing-strings">Passing strings</a></li> <li><a class="reference internal" href="#passing-iterators">Passing iterators</a></li> <li><a class="reference internal" href="#setting-header-fields">Setting header fields</a></li> <li><a class="reference internal" href="#telling-the-browser-to-treat-the-response-as-a-file-attachment">Telling the browser to treat the response as a file attachment</a></li> </ul> </li> <li><a class="reference internal" href="#id2">Attributes</a></li> <li><a class="reference internal" href="#id3">Methods</a></li> <li><a class="reference internal" href="#httpresponse-subclasses">HttpResponse subclasses</a></li> </ul> </li> <li><a class="reference internal" href="#jsonresponse-objects">JsonResponse objects</a><ul> <li><a class="reference internal" href="#id4">Usage</a><ul> <li><a class="reference internal" href="#serializing-non-dictionary-objects">Serializing non-dictionary objects</a></li> <li><a class="reference internal" href="#changing-the-default-json-encoder">Changing the default JSON encoder</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#streaminghttpresponse-objects">StreamingHttpResponse objects</a><ul> <li><a class="reference internal" href="#id5">Attributes</a></li> </ul> </li> <li><a class="reference internal" href="#fileresponse-objects">FileResponse objects</a></li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="models/database-functions.html">Database Functions</a></li> <li>Next: <a href="schema-editor.html"><code class="docutils literal"><span class="pre">SchemaEditor</span></code></a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../index.html">Django 1.8.19 documentation</a> <ul><li><a href="index.html">API Reference</a> <ul><li>Request and response objects</li></ul> </li></ul> </li> </ul> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/ref/request-response.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Mar 10, 2018</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="models/database-functions.html" title="Database Functions">previous</a> | <a href="index.html" title="API Reference" accesskey="U">up</a> | <a href="schema-editor.html" title="<code class="docutils literal"><span class="pre">SchemaEditor</span></code>">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>