Django shortcut functions¶
The packagedjango.shortcuts collects helper functions and classes that“span” multiple levels of MVC. In other words, these functions/classesintroduce controlled coupling for convenience’s sake.
render()¶
render(request,template_name,context=None,content_type=None,status=None,using=None)[source]¶Combines a given template with a given context dictionary and returns an
HttpResponseobject with that rendered text.Django does not provide a shortcut function which returns a
TemplateResponsebecause the constructorofTemplateResponseoffers the same levelof convenience asrender().
Required arguments¶
request- The request object used to generate this response.
template_name- The full name of a template to use or sequence of template names. If asequence is given, the first template that exists will be used. See thetemplate loading documentation for moreinformation on how templates are found.
Optional arguments¶
context- A dictionary of values to add to the template context. By default, thisis an empty dictionary. If a value in the dictionary is callable, theview will call it just before rendering the template.
content_type- The MIME type to use for the resulting document. Defaults to the value ofthe
DEFAULT_CONTENT_TYPEsetting. status- The status code for the response. Defaults to
200. using- The
NAMEof a template engine to use forloading the template.
Example¶
The following example renders the templatemyapp/index.html with theMIME typeapplication/xhtml+xml:
fromdjango.shortcutsimportrenderdefmy_view(request):# View code here...returnrender(request,'myapp/index.html',{'foo':'bar',},content_type='application/xhtml+xml')
This example is equivalent to:
fromdjango.httpimportHttpResponsefromdjango.templateimportloaderdefmy_view(request):# View code here...t=loader.get_template('myapp/index.html')c={'foo':'bar'}returnHttpResponse(t.render(c,request),content_type='application/xhtml+xml')
render_to_response()¶
redirect()¶
redirect(to,permanent=False,*args,**kwargs)[source]¶Returns an
HttpResponseRedirectto the appropriate URLfor the arguments passed.The arguments could be:
- A model: the model’s
get_absolute_url()function will be called. - A view name, possibly with arguments:
reverse()will beused to reverse-resolve the name. - An absolute or relative URL, which will be used as-is for the redirectlocation.
By default issues a temporary redirect; pass
permanent=Trueto issue apermanent redirect.- A model: the model’s
Examples¶
You can use theredirect() function in a number of ways.
By passing some object; that object’s
get_absolute_url()method will be calledto figure out the redirect URL:fromdjango.shortcutsimportredirectdefmy_view(request):...object=MyModel.objects.get(...)returnredirect(object)
By passing the name of a view and optionally some positional orkeyword arguments; the URL will be reverse resolved using the
reverse()method:defmy_view(request):...returnredirect('some-view-name',foo='bar')
By passing a hardcoded URL to redirect to:
defmy_view(request):...returnredirect('/some/url/')
This also works with full URLs:
defmy_view(request):...returnredirect('https://example.com/')
By default,redirect() returns a temporary redirect. All of the aboveforms accept apermanent argument; if set toTrue a permanent redirectwill be returned:
defmy_view(request):...object=MyModel.objects.get(...)returnredirect(object,permanent=True)
get_object_or_404()¶
get_object_or_404(klass,*args,**kwargs)[source]¶Calls
get()on a given model manager,but it raisesHttp404instead of the model’sDoesNotExistexception.
Required arguments¶
Example¶
The following example gets the object with the primary key of 1 fromMyModel:
fromdjango.shortcutsimportget_object_or_404defmy_view(request):my_object=get_object_or_404(MyModel,pk=1)
This example is equivalent to:
fromdjango.httpimportHttp404defmy_view(request):try:my_object=MyModel.objects.get(pk=1)exceptMyModel.DoesNotExist:raiseHttp404("No MyModel matches the given query.")
The most common use case is to pass aModel, asshown above. However, you can also pass aQuerySet instance:
queryset=Book.objects.filter(title__startswith='M')get_object_or_404(queryset,pk=1)
The above example is a bit contrived since it’s equivalent to doing:
get_object_or_404(Book,title__startswith='M',pk=1)
but it can be useful if you are passed thequeryset variable from somewhereelse.
Finally, you can also use aManager. This is usefulfor example if you have acustom manager:
get_object_or_404(Book.dahl_objects,title='Matilda')
You can also userelatedmanagers:
author=Author.objects.get(name='Roald Dahl')get_object_or_404(author.book_set,title='Matilda')
Note: As withget(), aMultipleObjectsReturned exceptionwill be raised if more than one object is found.
get_list_or_404()¶
get_list_or_404(klass,*args,**kwargs)[source]¶Returns the result of
filter()on agiven model manager cast to a list, raisingHttp404ifthe resulting list is empty.
Required arguments¶
Example¶
The following example gets all published objects fromMyModel:
fromdjango.shortcutsimportget_list_or_404defmy_view(request):my_objects=get_list_or_404(MyModel,published=True)
This example is equivalent to:
fromdjango.httpimportHttp404defmy_view(request):my_objects=list(MyModel.objects.filter(published=True))ifnotmy_objects:raiseHttp404("No MyModel matches the given query.")

