Ticket #14150: shortcuts.txt

File shortcuts.txt, 7.6 KB (added by wumzi, 14 years ago)

The new Shortcuts documentation

Line 
1.. _topics-http-shortcuts:
2
3=========================
4Django shortcut functions
5=========================
6
7.. module:: django.shortcuts
8 :synopsis:
9 Convience shortcuts that spam multiple levels of Django's MVC stack.
10
11.. index:: shortcuts
12
13The package ``django.shortcuts`` collects helper functions and classes that
14"span" multiple levels of MVC. In other words, these functions/classes
15introduce controlled coupling for convenience's sake.
16
17``render_to_response``
18======================
19
20.. function:: render_to_response(template[, dictionary][, context_instance][, mimetype])
21
22 Renders a given template with a given context dictionary and returns an
23 :class:`~django.http.HttpResponse` object with that rendered text.
24
25Required arguments
26------------------
27
28``template``
29 The full name of a template to use or sequence of template names.
30
31Optional arguments
32------------------
33
34``dictionary``
35 A dictionary of values to add to the template context. By default, this
36 is an empty dictionary. If a value in the dictionary is callable, the
37 view will call it just before rendering the template.
38
39``context_instance``
40 The context instance to render the template with. By default, the template
41 will be rendered with a ``Context`` instance (filled with values from
42 ``dictionary``). If you need to use :ref:`context processors
43 <subclassing-context-requestcontext>`, render the template with a
44 ``RequestContext`` instance instead. Your code might look something like
45 this::
46
47 return render_to_response('my_template.html',
48 my_data_dictionary,
49 context_instance=RequestContext(request))
50
51``mimetype``
52
53 .. versionadded:: 1.0
54
55 The MIME type to use for the resulting document. Defaults to the value of
56 the :setting:`DEFAULT_CONTENT_TYPE` setting.
57
58Example
59-------
60
61The following example renders the template ``myapp/index.html`` with the
62MIME type ``application/xhtml+xml``::
63
64 from django.shortcuts import render_to_response
65
66 def my_view(request):
67 # View code here...
68 return render_to_response('myapp/index.html', {"foo": "bar"},
69 mimetype="application/xhtml+xml")
70
71This example is equivalent to::
72
73 from django.http import HttpResponse
74 from django.template import Context, loader
75
76 def my_view(request):
77 # View code here...
78 t = loader.get_template('myapp/template.html')
79 c = Context({'foo': 'bar'})
80 return HttpResponse(t.render(c),
81 mimetype="application/xhtml+xml")
82
83``redirect``
84============
85
86.. function:: redirect(to[, permanent=False], *args, **kwargs)
87
88 .. versionadded:: 1.1
89
90 Returns an HttpResponseRedirect to the apropriate URL for the arguments
91 passed.
92
93 The arguments could be:
94
95 * A model: the model's `get_absolute_url()` function will be called.
96
97 * A view name, possibly with arguments: `urlresolvers.reverse()` will
98 be used to reverse-resolve the name.
99
100 * A URL, which will be used as-is for the redirect location.
101
102 By default issues a temporary redirect; pass permanent=True to issue a
103 permanent redirect
104
105Examples
106--------
107
108You can use the :func:`redirect` function in a number of ways.
109
110 1. By passing some object; that object's
111 :meth:`~django.db.models.Model.get_absolute_url` method will be called
112 to figure out the redirect URL::
113
114 def my_view(request):
115 ...
116 object = MyModel.objects.get(...)
117 return redirect(object)
118
119 2. By passing the name of a view and optionally some positional or
120 keyword arguments; the URL will be reverse resolved using the
121 :func:`~django.core.urlresolvers.reverse` method::
122
123 def my_view(request):
124 ...
125 return redirect('some-view-name', foo='bar')
126
127 3. By passing a hardcoded URL to redirect to::
128
129 def my_view(request):
130 ...
131 return redirect('/some/url/')
132
133 This also works with full URLs::
134
135 def my_view(request):
136 ...
137 return redirect('http://example.com/')
138
139By default, :func:`redirect` returns a temporary redirect. All of the above
140forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
141will be returned::
142
143 def my_view(request):
144 ...
145 object = MyModel.objects.get(...)
146 return redirect(object, permanent=True)
147
148``get_object_or_404``
149=====================
150
151.. function:: get_object_or_404(klass, *args, **kwargs)
152
153 Calls :meth:`~django.db.models.QuerySet.get()` on a given model manager,
154 but it raises ``django.http.Http404`` instead of the model's
155 ``DoesNotExist`` exception.
156
157Required arguments
158------------------
159
160``klass``
161 A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the
162 object.
163
164``**kwargs``
165 Lookup parameters, which should be in the format accepted by ``get()`` and
166 ``filter()``.
167
168Example
169-------
170
171The following example gets the object with the primary key of 1 from
172``MyModel``::
173
174 from django.shortcuts import get_object_or_404
175
176 def my_view(request):
177 my_object = get_object_or_404(MyModel, pk=1)
178
179This example is equivalent to::
180
181 from django.http import Http404
182
183 def my_view(request):
184 try:
185 my_object = MyModel.objects.get(pk=1)
186 except MyModel.DoesNotExist:
187 raise Http404
188
189Note: As with ``get()``, an ``MultipleObjectsReturned`` exception will be
190raised if more than one object is found.
191
192``get_objects_or_404``
193===================
194
195.. function:: get_objects_or_404(klass, *args, **kwargs)
196
197 Returns the result of :meth:`~django.db.models.QuerySet.filter()` on a
198 given model manager, raising ``django.http.Http404`` if no objects matched.
199
200Required arguments
201------------------
202
203``klass``
204 A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the
205 object.
206
207``**kwargs``
208 Lookup parameters, which should be in the format accepted by ``get()`` and
209 ``filter()``.
210
211Example
212-------
213
214The following example gets all published objects from ``MyModel``::
215
216 from django.shortcuts import get_objects_or_404
217
218 def my_view(request):
219 my_objects = get_objects_or_404(MyModel, published=True)
220
221This example is equivalent to::
222
223 from django.http import Http404
224
225 def my_view(request):
226 my_objects = MyModel.objects.filter(published=True)
227 if not my_objects:
228 raise Http404
229
230Because get_objects_or_404 returns a queryset, it's possible to continue
231editing it:
232
233 from django.shortcuts import get_objects_or_404
234
235 def my_view(request):
236 my_objects = get_objects_or_404(MyModel, published=True).order_by('pub_date')
237
238``get_list_or_404``
239===================
240
241.. function:: get_list_or_404(klass, *args, **kwargs)
242
243 Returns the result of :meth:`~django.db.models.QuerySet.filter()` on a
244 given model manager, raising ``django.http.Http404`` if the resulting list
245 is empty.
246
247Required arguments
248------------------
249
250``klass``
251 A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the
252 object.
253
254``**kwargs``
255 Lookup parameters, which should be in the format accepted by ``get()`` and
256 ``filter()``.
257
258Example
259-------
260
261The following example gets all published objects from ``MyModel``::
262
263 from django.shortcuts import get_list_or_404
264
265 def my_view(request):
266 my_objects = get_list_or_404(MyModel, published=True)
267
268This example is equivalent to::
269
270 from django.http import Http404
271
272 def my_view(request):
273 my_objects = list(MyModel.objects.filter(published=True))
274 if not my_objects:
275 raise Http404
Back to Top