Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 539 lines (405 sloc) 24.168 kB
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
1 ========================================
2 Appendix G: Request and Response Objects
3 ========================================
4
5 Django uses request and response objects to pass state through the system.
6
7 When a page is requested, Django creates an ``HttpRequest`` object that
8 contains metadata about the request. Then Django loads the appropriate view,
9 passing the ``HttpRequest`` as the first argument to the view function. Each
10 view is responsible for returning an ``HttpResponse`` object.
11
12 We've used these objects often throughout the book; this appendix explains the
13 complete APIs for ``HttpRequest`` and ``HttpResponse`` objects.
14
15 HttpRequest
16 ===========
17
18 ``HttpRequest`` represents a single HTTP request from some user-agent.
19
20 Much of the important information about the request is available as attributes
21 on the ``HttpRequest`` instance (see Table G-1). All attributes except
22 ``session`` should be considered read-only.
23
24 .. table:: Table G-1. Attributes of HttpRequest Objects
25
26 ================== =======================================================
27 Attribute Description
28 ================== =======================================================
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
29 ``path`` A string representing the full path to the requested
30 page, not including the domain -- for example,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
31 ``"/music/bands/the_beatles/"``.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
32
33 ``method`` A string representing the HTTP method used in the
34 request. This is guaranteed to be uppercase. For
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
35 example::
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
36
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
37 if request.method == 'GET':
38 do_something()
39 elif request.method == 'POST':
40 do_something_else()
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
41
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
42 ``encoding`` A string representing the current encoding used to
43 decode form submission data (or ``None``, which means
44 the ``DEFAULT_CHARSET`` setting is used).
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
45
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
46 You can write to this attribute to change the encoding
47 used when accessing the form data. Any subsequent
48 attribute accesses (such as reading from ``GET`` or
49 ``POST``) will use the new ``encoding`` value. Useful
50 if you know the form data is not in the
51 ``DEFAULT_CHARSET`` encoding.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
52
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
53 ``GET`` A dictionary-like object containing all given HTTP GET
54 parameters. See the upcoming ``QueryDict`` documentation.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
55
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
56 ``POST`` A dictionary-like object containing all given HTTP POST
57 parameters. See the upcoming ``QueryDict`` documentation.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
58
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
59 It's possible that a request can come in via POST with
60 an empty ``POST`` dictionary -- if, say, a form is
61 requested via the POST HTTP method but does not
62 include form data. Therefore, you shouldn't use ``if
63 request.POST`` to check for use of the POST method;
64 instead, use ``if request.method == "POST"`` (see
65 the ``method`` entry in this table).
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
66
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
67 Note: ``POST`` does *not* include file-upload
68 information. See ``FILES``.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
69
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
70 ``REQUEST`` For convenience, a dictionary-like object that searches
71 ``POST`` first, and then ``GET``. Inspired by PHP's
72 ``$_REQUEST``.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
73
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
74 For example, if ``GET = {"name": "john"}`` and ``POST
75 = {"age": '34'}``, ``REQUEST["name"]`` would be
76 ``"john"``, and ``REQUEST["age"]`` would be ``"34"``.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
77
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
78 It's strongly suggested that you use ``GET`` and
79 ``POST`` instead of ``REQUEST``, because the former
80 are more explicit.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
81
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
82 ``COOKIES`` A standard Python dictionary containing all cookies.
83 Keys and values are strings. See Chapter 14 for more
84 on using cookies.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
85
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
86 ``FILES`` A dictionary-like object that maps filenames to
87 ``UploadedFile`` objects. See the Django
88 documentation for more.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
89
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
90 ``META`` A standard Python dictionary containing all available
91 HTTP headers. Available headers depend on the client
92 and server, but here are some examples:
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
93
94 * ``CONTENT_LENGTH``
95 * ``CONTENT_TYPE``
96 * ``QUERY_STRING``: The raw unparsed query string
97 * ``REMOTE_ADDR``: The IP address of the client
98 * ``REMOTE_HOST``: The hostname of the client
99 * ``SERVER_NAME``: The hostname of the server.
100 * ``SERVER_PORT``: The port of the server
101
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
102 Any HTTP headers are available in ``META`` as keys
103 prefixed with ``HTTP_``, converted to uppercase and
104 substituting underscores for hyphens. For example:
105
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
106 * ``HTTP_ACCEPT_ENCODING``
107 * ``HTTP_ACCEPT_LANGUAGE``
108 * ``HTTP_HOST``: The HTTP ``Host`` header sent by
109 the client
110 * ``HTTP_REFERER``: The referring page, if any
111 * ``HTTP_USER_AGENT``: The client's user-agent string
112 * ``HTTP_X_BENDER``: The value of the ``X-Bender``
113 header, if set
114
115 ``user`` A ``django.contrib.auth.models.User`` object
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
116 representing the currently logged-in user. If the user
117 isn't currently logged in, ``user`` will be set to an
118 instance of
119 ``django.contrib.auth.models.AnonymousUser``. You can
120 tell them apart with ``is_authenticated()``, like so::
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
121
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
122 if request.user.is_authenticated():
123 # Do something for logged-in users.
124 else:
125 # Do something for anonymous users.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
126
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
127 ``user`` is available only if your Django installation
128 has the ``AuthenticationMiddleware`` activated.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
129
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
130 For the complete details of authentication and users,
131 see Chapter 14.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
132
133 ``session`` A readable and writable, dictionary-like object that
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
134 represents the current session. This is available only
135 if your Django installation has session support
136 activated. See Chapter 14.
137
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
138 ``raw_post_data`` The raw HTTP POST data. This is useful for advanced
139 processing.
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
140 ================== =======================================================
141
142 Request objects also have a few useful methods, as shown in Table G-2.
143
144 .. table:: Table G-2. HttpRequest Methods
145
146 ====================== ===================================================
147 Method Description
148 ====================== ===================================================
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
149 ``__getitem__(key)`` Returns the GET/POST value for the given key,
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
150 checking POST first, and then GET. Raises
151 ``KeyError`` if the key doesn't exist.
152
153 This lets you use dictionary-accessing syntax on
154 an ``HttpRequest`` instance.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
155
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
156 For example, ``request["foo"]`` is the same as
157 checking ``request.POST["foo"]`` and then
158 ``request.GET["foo"]``.
159
160 ``has_key()`` Returns ``True`` or ``False``, designating whether
161 ``request.GET`` or ``request.POST`` has the given
162 key.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
163
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
164 ``get_host()`` Returns the originating host of the request using
165 information from the ``HTTP_X_FORWARDED_HOST`` and
166 ``HTTP_HOST`` headers (in that order). If they
167 don't provide a value, the method uses a
168 combination of ``SERVER_NAME`` and
169 ``SERVER_PORT``.
170
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
171 ``get_full_path()`` Returns the ``path``, plus an appended query
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
172 string, if applicable. For example,
173 ``"/music/bands/the_beatles/?print=true"``
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
174
175 ``is_secure()`` Returns ``True`` if the request is secure; that
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
176 is, if it was made with HTTPS.
177 ====================== ===================================================
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
178
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
179 QueryDict Objects
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
180 -----------------
181
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
182 In an ``HttpRequest`` object, the ``GET`` and ``POST`` attributes are
183 instances of ``django.http.QueryDict``. ``QueryDict`` is a dictionary-like
184 class customized to deal with multiple values for the same key. This is
185 necessary because some HTML form elements, notably ``<select
186 multiple="multiple">``, pass multiple values for the same key.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
187
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
188 ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
189 That means you can't change attributes of ``request.POST`` and ``request.GET``
190 directly.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
191
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
192 ``QueryDict`` implements the all standard dictionary methods, because it's a
193 subclass of dictionary. Exceptions are outlined in Table G-3.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
194
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
195 .. table:: Table G-3. How QueryDicts Differ from Standard Dictionaries.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
196
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
197 ================== =======================================================
198 Method Differences from Standard dict Implementation
199 ================== =======================================================
200 ``__getitem__`` Works just like a dictionary. However, if the key
201 has more than one value, ``__getitem__()`` returns the
202 last value.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
203
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
204 ``__setitem__`` Sets the given key to ``[value]`` (a Python list whose
205 single element is ``value``). Note that this, as other
206 dictionary functions that have side effects, can
207 be called only on a mutable ``QueryDict`` (one that was
208 created via ``copy()``).
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
209
210 ``get()`` If the key has more than one value, ``get()`` returns
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
211 the last value just like ``__getitem__``.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
212
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
213 ``update()`` Takes either a ``QueryDict`` or standard dictionary.
214 Unlike the standard dictionary's ``update`` method,
215 this method *appends* to the current dictionary items
216 rather than replacing them::
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
217
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
218 >>> q = QueryDict('a=1')
219 >>> q = q.copy() # to make it mutable
220 >>> q.update({'a': '2'})
221 >>> q.getlist('a')
222 ['1', '2']
223 >>> q['a'] # returns the last
224 ['2']
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
225
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
226 ``items()`` Just like the standard dictionary ``items()`` method,
227 except this uses the same last-value logic as
228 ``__getitem()__``::
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
229
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
230 >>> q = QueryDict('a=1&a=2&a=3')
231 >>> q.items()
232 [('a', '3')]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
233
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
234 ``values()`` Just like the standard dictionary ``values()`` method,
235 except this uses the same last-value logic as
236 ``__getitem()__``.
237 ================== =======================================================
238
239 In addition, ``QueryDict`` has the methods shown in Table G-4.
240
241 .. table:: G-4. Extra (Nondictionary) QueryDict Methods
242
243 ========================== ===============================================
244 Method Description
245 ========================== ===============================================
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
246 ``copy()`` Returns a copy of the object, using
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
247 ``copy.deepcopy()`` from the Python standard
248 library. The copy will be mutable -- that is,
249 you can change its values.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
250
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
251 ``getlist(key)`` Returns the data with the requested key, as a
252 Python list. Returns an empty list if the key
253 doesn't exist. It's guaranteed to return a
254 list of some sort.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
255
256 ``setlist(key, list_)`` Sets the given key to ``list_`` (unlike
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
257 ``__setitem__()``).
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
258
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
259 ``appendlist(key, item)`` Appends an item to the internal list associated
260 with ``key``.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
261
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
262 ``setlistdefault(key, a)`` Just like ``setdefault``, except it takes a
263 list of values instead of a single value.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
264
265 ``lists()`` Like ``items()``, except it includes all
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
266 values, as a list, for each member of the
267 dictionary. For example::
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
268
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
269 >>> q = QueryDict('a=1&a=2&a=3')
270 >>> q.lists()
271 [('a', ['1', '2', '3'])]
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
272
273
274 ``urlencode()`` Returns a string of the data in query-string
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
275 format (e.g., ``"a=2&b=3&b=5"``).
276 ========================== ===============================================
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
277
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
278 A Complete Example
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
279 ------------------
280
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
281 For example, given this HTML form::
282
283 <form action="/foo/bar/" method="post">
284 <input type="text" name="your_name" />
285 <select multiple="multiple" name="bands">
286 <option value="beatles">The Beatles</option>
287 <option value="who">The Who</option>
288 <option value="zombies">The Zombies</option>
289 </select>
290 <input type="submit" />
291 </form>
292
293 if the user enters ``"John Smith"`` in the ``your_name`` field and selects
294 both "The Beatles" and "The Zombies" in the multiple select box, here's what
295 Django's request object would have::
296
297 >>> request.GET
298 {}
299 >>> request.POST
300 {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']}
301 >>> request.POST['your_name']
302 'John Smith'
303 >>> request.POST['bands']
304 'zombies'
305 >>> request.POST.getlist('bands')
306 ['beatles', 'zombies']
307 >>> request.POST.get('your_name', 'Adrian')
308 'John Smith'
309 >>> request.POST.get('nonexistent_field', 'Nowhere Man')
310 'Nowhere Man'
311
312 .. admonition:: Implementation Note:
313
314 The ``GET``, ``POST``, ``COOKIES``, ``FILES``, ``META``, ``REQUEST``,
315 ``raw_post_data``, and ``user`` attributes are all lazily loaded. That means
316 Django doesn't spend resources calculating the values of those attributes until
317 your code requests them.
318
319 HttpResponse
320 ============
321
322 In contrast to ``HttpRequest`` objects, which are created automatically by
323 Django, ``HttpResponse`` objects are your responsibility. Each view you write
324 is responsible for instantiating, populating, and returning an
325 ``HttpResponse``.
326
327 The ``HttpResponse`` class lives at ``django.http.HttpResponse``.
328
329 Construction HttpResponses
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
330 --------------------------
331
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
332 Typically, you'll construct an ``HttpResponse`` to pass the contents of the
333 page, as a string, to the ``HttpResponse`` constructor::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
334
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
335 >>> response = HttpResponse("Here's the text of the Web page.")
336 >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
337
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
338 But if you want to add content incrementally, you can use ``response`` as a
339 filelike object::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
340
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
341 >>> response = HttpResponse()
342 >>> response.write("<p>Here's the text of the Web page.</p>")
343 >>> response.write("<p>Here's another paragraph.</p>")
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
344
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
345 You can pass ``HttpResponse`` an iterator rather than passing it
346 hard-coded strings. If you use this technique, follow these guidelines:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
347
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
348 * The iterator should return strings.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
349
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
350 * If an ``HttpResponse`` has been initialized with an iterator as its
351 content, you can't use the ``HttpResponse`` instance as a filelike
352 object. Doing so will raise ``Exception``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
353
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
354 Finally, note that ``HttpResponse`` implements a ``write()`` method, which
355 makes is suitable for use anywhere that Python expects a filelike object. See
356 Chapter 8 for some examples of using this technique.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
357
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
358 Setting Headers
359 ---------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
360
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
361 You can add and delete headers using dictionary syntax::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
362
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
363 >>> response = HttpResponse()
364 >>> response['X-DJANGO'] = "It's the best."
365 >>> del response['X-PHP']
366 >>> response['X-DJANGO']
367 "It's the best."
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
368
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
369 You can also use ``has_header(header)`` to check for the existence of a header.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
370
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
371 Avoid setting ``Cookie`` headers by hand; instead, see Chapter 14 for
372 instructions on how cookies work in Django.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
373
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
374 HttpResponse Subclasses
375 -----------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
376
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
377 Django includes a number of ``HttpResponse`` subclasses that handle different
378 types of HTTP responses (see Table G-5). Like ``HttpResponse``, these subclasses live in
379 ``django.http``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
380
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
381 .. table:: Table G-5. HttpResponse Subclasses
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
382
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
383 ================================== =======================================
384 Class Description
385 ================================== =======================================
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
386 ``HttpResponseRedirect`` The constructor takes a single argument:
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
387 the path to redirect to. This can
388 be a fully qualified URL (e.g.,
389 ``'http://search.yahoo.com/'``) or
390 an absolute URL with no domain (e.g.,
391 ``'/search/'``). Note that this
392 returns an HTTP status code 302.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
393
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
394 ``HttpResponsePermanentRedirect`` Like ``HttpResponseRedirect``, but it
395 returns a permanent redirect (HTTP
396 status code 301) instead of a "found"
397 redirect (status code 302).
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
398
399 ``HttpResponseNotModified`` The constructor doesn't take any
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
400 arguments. Use this to designate that
401 a page hasn't been modified since the
402 user's last request.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
403
404 ``HttpResponseBadRequest`` Acts just like ``HttpResponse`` but
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
405 uses a 400 status code.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
406
407 ``HttpResponseNotFound`` Acts just like ``HttpResponse`` but
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
408 uses a 404 status code.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
409
410 ``HttpResponseForbidden`` Acts just like ``HttpResponse`` but
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
411 uses a 403 status code.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
412
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
413 ``HttpResponseNotAllowed`` Like ``HttpResponse``, but uses a 405
414 status code. It takes a single, required
415 argument: a list of permitted methods
416 (e.g., ``['GET', 'POST']``).
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
417
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
418 ``HttpResponseGone`` Acts just like ``HttpResponse`` but
419 uses a 410 status code.
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
420
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
421 ``HttpResponseServerError`` Acts just like ``HttpResponse`` but
422 uses a 500 status code.
423 ================================== =======================================
424
425 You can, of course, define your own ``HttpResponse`` subclass to support
426 different types of responses not supported out of the box.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
427
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
428 Returning Errors
429 ----------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
430
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
431 Returning HTTP error codes in Django is easy. We've already mentioned the
432 ``HttpResponseNotFound``, ``HttpResponseForbidden``,
433 ``HttpResponseServerError``, and other subclasses. Just return an instance of one
434 of those subclasses instead of a normal ``HttpResponse`` in order to signify
435 an error, for example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
436
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
437 def my_view(request):
438 # ...
439 if foo:
440 return HttpResponseNotFound('<h1>Page not found</h1>')
441 else:
442 return HttpResponse('<h1>Page was found</h1>')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
443
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
444 Because a 404 error is by far the most common HTTP error, there's an easier
445 way to handle it.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
446
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
447 When you return an error such as ``HttpResponseNotFound``, you're responsible
448 for defining the HTML of the resulting error page::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
449
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
450 return HttpResponseNotFound('<h1>Page not found</h1>')
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
451
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
452 For convenience, and because it's a good idea to have a consistent 404 error page
453 across your site, Django provides an ``Http404`` exception. If you raise
454 ``Http404`` at any point in a view function, Django will catch it and return the
455 standard error page for your application, along with an HTTP error code 404.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
456
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
457 Here's an example::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
458
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
459 from django.http import Http404
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
460
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
461 def detail(request, poll_id):
462 try:
463 p = Poll.objects.get(pk=poll_id)
464 except Poll.DoesNotExist:
465 raise Http404
466 return render_to_response('polls/detail.html', {'poll': p})
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
467
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
468 In order to use the ``Http404`` exception to its fullest, you should create a
469 template that is displayed when a 404 error is raised. This template should be
470 called ``404.html``, and it should be located in the top level of your template tree.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
471
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
472 Customizing the 404 (Not Found) View
473 ------------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
474
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
475 When you raise an ``Http404`` exception, Django loads a special view devoted
476 to handling 404 errors. By default, it's the view
477 ``django.views.defaults.page_not_found``, which loads and renders the template
478 ``404.html``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
479
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
480 This means you need to define a ``404.html`` template in your root template
481 directory. This template will be used for all 404 errors.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
482
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
483 This ``page_not_found`` view should suffice for 99% of Web applications, but
484 if you want to override the 404 view, you can specify ``handler404`` in your
485 URLconf, like so::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
486
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
487 from django.conf.urls.defaults import *
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
488
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
489 urlpatterns = patterns('',
490 ...
491 )
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
492
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
493 handler404 = 'mysite.views.my_custom_404_view'
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
494
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
495 Behind the scenes, Django determines the 404 view by looking for
496 ``handler404``. By default, URLconfs contain the following line::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
497
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
498 from django.conf.urls.defaults import *
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
499
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
500 That takes care of setting ``handler404`` in the current module. As you can
501 see in ``django/conf/urls/defaults.py``, ``handler404`` is set to
502 ``'django.views.defaults.page_not_found'`` by default.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
503
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
504 There are three things to note about 404 views:
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
505
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
506 * The 404 view is also called if Django doesn't find a match after checking
507 every regular expression in the URLconf.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
508
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
509 * If you don't define your own 404 view -- and simply use the default,
510 which is recommended -- you still have one obligation: to create a
511 ``404.html`` template in the root of your template directory. The default
512 404 view will use that template for all 404 errors.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
513
fdc4800 @jacobian Fixed a bunch of reST markup errors.
jacobian authored
514 * If ``DEBUG`` is set to ``True`` (in your settings module), then your 404
515 view will never be used, and the traceback will be displayed instead.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
516
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
517 Customizing the 500 (Server Error) View
518 ---------------------------------------
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
519
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
520 Similarly, Django executes special-case behavior in the case of runtime errors
521 in view code. If a view results in an exception, Django will, by default, call
522 the view ``django.views.defaults.server_error``, which loads and renders the
523 template ``500.html``.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
524
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
525 This means you need to define a ``500.html`` template in your root template
526 directory. This template will be used for all server errors.
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
527
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
528 This ``server_error`` view should suffice for 99% of Web applications, but if
529 you want to override the view, you can specify ``handler500`` in your
530 URLconf, like so::
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
531
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
532 from django.conf.urls.defaults import *
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
533
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
534 urlpatterns = patterns('',
535 ...
536 )
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
537
d40cfe7 @jacobian Restored *2.0* version of the book, not 1.0!
jacobian authored
538 handler500 = 'mysite.views.my_custom_error_view'
Something went wrong with that request. Please try again.