Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentation

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 anHttpResponse object with that rendered text.

Django does not provide a shortcut function which returns aTemplateResponse because the constructorofTemplateResponse offers 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 oftheDEFAULT_CONTENT_TYPE setting.
status
The status code for the response. Defaults to200.
using
TheNAME of 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()

render_to_response(template_name,context=None,content_type=None,status=None,using=None)[source]

This function preceded the introduction ofrender() and workssimilarly except that it doesn’t make therequest available in theresponse. It’s not recommended and is likely to be deprecated in the future.

redirect()

redirect(to,permanent=False,*args,**kwargs)[source]

Returns anHttpResponseRedirect to the appropriate URLfor the arguments passed.

The arguments could be:

  • A model: the model’sget_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; passpermanent=True to issue apermanent redirect.

Examples

You can use theredirect() function in a number of ways.

  1. By passing some object; that object’sget_absolute_url() method will be calledto figure out the redirect URL:

    fromdjango.shortcutsimportredirectdefmy_view(request):...object=MyModel.objects.get(...)returnredirect(object)
  2. By passing the name of a view and optionally some positional orkeyword arguments; the URL will be reverse resolved using thereverse() method:

    defmy_view(request):...returnredirect('some-view-name',foo='bar')
  3. 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]

Callsget() on a given model manager,but it raisesHttp404 instead of the model’sDoesNotExist exception.

Required arguments

klass
AModel class,aManager,or aQuerySet instance from which to getthe object.
**kwargs
Lookup parameters, which should be in the format accepted byget() andfilter().

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 offilter() on agiven model manager cast to a list, raisingHttp404 ifthe resulting list is empty.

Required arguments

klass
AModel,Manager orQuerySet instance from which to get thelist.
**kwargs
Lookup parameters, which should be in the format accepted byget() andfilter().

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.")
Back to Top

Additional Information

Support Django!

Support Django!

Contents

Getting help

FAQ
Try the FAQ — it's got answers to many common questions.
Index,Module Index, orTable of Contents
Handy when looking for specific information.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (Django 1.10):HTML |PDF |ePub
Provided byRead the Docs.

Diamond and Platinum Members

Sentry
JetBrains
This document is for an insecure version of Django that is no longer supported. Please upgrade to a newer release!

[8]ページ先頭

©2009-2025 Movatter.jp