PageRenderTime 5ms CodeModel.GetById 2ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/http/shortcuts.txt

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