1 =========================
2 Django shortcut functions
3 =========================
5 The package ``django.shortcuts`` collects helper functions and classes that
6 "span" multiple levels of MVC. In other words, these functions/classes
7 introduce controlled coupling for convenience's sake.
9 ``render_to_response()``
10 ========================
12 ``django.shortcuts.render_to_response`` renders a given template with a given
13 context dictionary and returns an ``HttpResponse`` object with that rendered
20 The full name of a template to use.
26 A dictionary of values to add to the template context. By default, this
27 is an empty dictionary. If a value in the dictionary is callable, the
28 view will call it just before rendering the template.
31 **New in Django development version:** The MIME type to use for the
32 resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE``
38 The following example renders the template ``myapp/index.html`` with the
39 MIME type ``application/xhtml+xml``::
41 from django.shortcuts import render_to_response
45 return render_to_response('myapp/index.html', {"foo": "bar"},
46 mimetype="application/xhtml+xml")
48 This example is equivalent to::
50 from django.http import HttpResponse
51 from django.template import Context, loader
55 t = loader.get_template('myapp/template.html')
56 c = Context({'foo': 'bar'})
57 r = HttpResponse(t.render(c),
58 mimetype="application/xhtml+xml")
60 .. _an HttpResponse object: ../request_response/#httpresponse-objects
65 ``django.shortcuts.get_object_or_404`` calls `get()`_ on a given model
66 manager, but it raises ``django.http.Http404`` instead of the model's
67 ``DoesNotExist`` exception.
73 A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the
77 Lookup parameters, which should be in the format accepted by ``get()`` and
83 The following example gets the object with the primary key of 1 from
86 from django.shortcuts import get_object_or_404
89 my_object = get_object_or_404(MyModel, pk=1)
91 This example is equivalent to::
93 from django.http import Http404
97 my_object = MyModel.object.get(pk=1)
98 except MyModel.DoesNotExist:
101 Note: As with ``get()``, an ``AssertionError`` will be raised if more than
104 .. _get(): ../db-api/#get-kwargs
109 ``django.shortcuts.get_list_or_404`` returns the result of `filter()`_ on a
110 given model manager, raising ``django.http.Http404`` if the resulting list is
117 A ``Model``, ``Manager`` or ``QuerySet`` instance from which to get the
121 Lookup parameters, which should be in the format accepted by ``get()`` and
127 The following example gets all published objects from ``MyModel``::
129 from django.shortcuts import get_list_or_404
131 def my_view(request):
132 my_objects = get_list_or_404(MyModel, published=True)
134 This example is equivalent to::
136 from django.http import Http404
138 def my_view(request):
139 my_objects = MyModels.object.filter(published=True)
143 .. _filter(): ../db-api/#filter-kwargs