mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-15 22:26:57 +03:00
907 lines
47 KiB
HTML
907 lines
47 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
|
<meta charset="utf-8">
|
|
<title>Renderers - Django REST framework</title>
|
|
<link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
|
|
<link rel="canonical" href="http://www.django-rest-framework.org/api-guide/renderers/" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<meta name="description" content="Django, API, REST, Renderers">
|
|
<meta name="author" content="Tom Christie">
|
|
|
|
<!-- Le styles -->
|
|
<link href="../../css/prettify.css" rel="stylesheet">
|
|
<link href="../../css/bootstrap.css" rel="stylesheet">
|
|
<link href="../../css/bootstrap-responsive.css" rel="stylesheet">
|
|
<link href="../../css/default.css" rel="stylesheet">
|
|
|
|
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
|
|
<!--[if lt IE 9]>
|
|
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
|
|
<![endif]-->
|
|
|
|
<script type="text/javascript">
|
|
var _gaq = _gaq || [];
|
|
_gaq.push(['_setAccount', 'UA-18852272-2']);
|
|
_gaq.push(['_trackPageview']);
|
|
|
|
(function() {
|
|
var ga = document.createElement('script');
|
|
ga.type = 'text/javascript';
|
|
ga.async = true;
|
|
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
|
|
var s = document.getElementsByTagName('script')[0];
|
|
s.parentNode.insertBefore(ga, s);
|
|
})();
|
|
</script>
|
|
|
|
<style>
|
|
#sidebarInclude img {
|
|
margin-bottom: 10px;
|
|
}
|
|
#sidebarInclude a.promo {
|
|
color: black;
|
|
}
|
|
@media (max-width: 767px) {
|
|
div.promo {
|
|
display: none;
|
|
}
|
|
}
|
|
</style>
|
|
</head>
|
|
<body onload="prettyPrint()" class="-page">
|
|
|
|
<div class="wrapper">
|
|
<div class="navbar navbar-inverse navbar-fixed-top">
|
|
<div class="navbar-inner">
|
|
<div class="container-fluid">
|
|
<a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
|
|
<a class="repo-link btn btn-inverse btn-small " rel="prev" href="../serializers/">
|
|
Next <i class="icon-arrow-right icon-white"></i>
|
|
</a>
|
|
<a class="repo-link btn btn-inverse btn-small " rel="next" href="../parsers/">
|
|
<i class="icon-arrow-left icon-white"></i> Previous
|
|
</a>
|
|
<a id="search_modal_show" class="repo-link btn btn-inverse btn-small" href="#mkdocs_search_modal" data-toggle="modal" data-target="#mkdocs_search_modal"><i class="icon-search icon-white"></i> Search</a>
|
|
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
<span class="icon-bar"></span>
|
|
</a>
|
|
<a class="brand" href="http://www.django-rest-framework.org">Django REST framework</a>
|
|
<div class="nav-collapse collapse">
|
|
|
|
<!-- Main navigation -->
|
|
<ul class="nav navbar-nav">
|
|
|
|
<li >
|
|
<a href="../..">Home</a>
|
|
</li>
|
|
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
|
|
<li >
|
|
<a href="../../tutorial/quickstart/">Quickstart</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/1-serialization/">1 - Serialization</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/2-requests-and-responses/">2 - Requests and responses</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/3-class-based-views/">3 - Class based views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/4-authentication-and-permissions/">4 - Authentication and permissions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/5-relationships-and-hyperlinked-apis/">5 - Relationships and hyperlinked APIs</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/6-viewsets-and-routers/">6 - Viewsets and routers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../tutorial/7-schemas-and-client-libraries/">7 - Schemas and client libraries</a>
|
|
</li>
|
|
|
|
</ul>
|
|
</li>
|
|
|
|
<li class="dropdown active">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
|
|
<li >
|
|
<a href="../requests/">Requests</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../responses/">Responses</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../views/">Views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../generic-views/">Generic views</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../viewsets/">Viewsets</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../routers/">Routers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../parsers/">Parsers</a>
|
|
</li>
|
|
|
|
<li class="active" >
|
|
<a href="./">Renderers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../serializers/">Serializers</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../fields/">Serializer fields</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../relations/">Serializer relations</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../validators/">Validators</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../authentication/">Authentication</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../permissions/">Permissions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../throttling/">Throttling</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../filtering/">Filtering</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../pagination/">Pagination</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../versioning/">Versioning</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../content-negotiation/">Content negotiation</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../metadata/">Metadata</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../schemas/">Schemas</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../format-suffixes/">Format suffixes</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../reverse/">Returning URLs</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../exceptions/">Exceptions</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../status-codes/">Status codes</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../testing/">Testing</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../settings/">Settings</a>
|
|
</li>
|
|
|
|
</ul>
|
|
</li>
|
|
|
|
<li class="dropdown">
|
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
|
|
<ul class="dropdown-menu">
|
|
|
|
<li >
|
|
<a href="../../topics/documenting-your-api/">Documenting your API</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/api-clients/">API Clients</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/internationalization/">Internationalization</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/ajax-csrf-cors/">AJAX, CSRF & CORS</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/html-and-forms/">HTML & Forms</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/browser-enhancements/">Browser Enhancements</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/browsable-api/">The Browsable API</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/rest-hypermedia-hateoas/">REST, Hypermedia & HATEOAS</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/third-party-resources/">Third Party Resources</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/contributing/">Contributing to REST framework</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/project-management/">Project management</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.0-announcement/">3.0 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.1-announcement/">3.1 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.2-announcement/">3.2 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.3-announcement/">3.3 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.4-announcement/">3.4 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/3.5-announcement/">3.5 Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/kickstarter-announcement/">Kickstarter Announcement</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/mozilla-grant/">Mozilla Grant</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/funding/">Funding</a>
|
|
</li>
|
|
|
|
<li >
|
|
<a href="../../topics/release-notes/">Release Notes</a>
|
|
</li>
|
|
|
|
</ul>
|
|
</li>
|
|
|
|
|
|
</ul>
|
|
|
|
</div>
|
|
<!--/.nav-collapse -->
|
|
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="body-content">
|
|
<div class="container-fluid">
|
|
<!-- Search Modal -->
|
|
<div id="mkdocs_search_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
|
|
<div class="modal-header">
|
|
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
|
|
<h3 id="myModalLabel">Documentation search</h3>
|
|
</div>
|
|
|
|
<div class="modal-body">
|
|
<form role="form" autocomplete="off">
|
|
<div class="form-group">
|
|
<input type="text" name="q" class="form-control" placeholder="Search..." id="mkdocs-search-query">
|
|
</div>
|
|
</form>
|
|
<div id="mkdocs-search-results"></div>
|
|
</div>
|
|
|
|
<div class="modal-footer">
|
|
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="row-fluid">
|
|
<div class="span3">
|
|
<div id="table-of-contents">
|
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
|
|
|
|
|
|
|
<li class="main">
|
|
<a href="#renderers">Renderers</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#how-the-renderer-is-determined">How the renderer is determined</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#setting-the-renderers">Setting the renderers</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#ordering-of-renderer-classes">Ordering of renderer classes</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#api-reference">API Reference</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#jsonrenderer">JSONRenderer</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#templatehtmlrenderer">TemplateHTMLRenderer</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#statichtmlrenderer">StaticHTMLRenderer</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#browsableapirenderer">BrowsableAPIRenderer</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#adminrenderer">AdminRenderer</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#htmlformrenderer">HTMLFormRenderer</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#multipartrenderer">MultiPartRenderer</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#custom-renderers">Custom renderers</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#data">data</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#media_typenone">media_type=None</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#renderer_contextnone">renderer_context=None</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#example">Example</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#setting-the-character-set">Setting the character set</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#advanced-renderer-usage">Advanced renderer usage</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#varying-behaviour-by-media-type">Varying behaviour by media type</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#underspecifying-the-media-type">Underspecifying the media type</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#designing-your-media-types">Designing your media types</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#html-error-views">HTML error views</a>
|
|
</li>
|
|
|
|
|
|
<li class="main">
|
|
<a href="#third-party-packages">Third party packages</a>
|
|
</li>
|
|
|
|
|
|
<li>
|
|
<a href="#yaml">YAML</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#xml">XML</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#jsonp">JSONP</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#messagepack">MessagePack</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#csv">CSV</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#ultrajson">UltraJSON</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#camelcase-json">CamelCase JSON</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#pandas-csv-excel-png">Pandas (CSV, Excel, PNG)</a>
|
|
</li>
|
|
|
|
<li>
|
|
<a href="#latex">LaTeX</a>
|
|
</li>
|
|
|
|
|
|
|
|
<div class="promo">
|
|
<hr/>
|
|
<div id="sidebarInclude">
|
|
</div>
|
|
</ul>
|
|
|
|
</div>
|
|
</div>
|
|
|
|
<div id="main-content" class="span9">
|
|
|
|
|
|
|
|
<a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/renderers.py">
|
|
<span class="label label-info">renderers.py</span>
|
|
</a>
|
|
|
|
|
|
|
|
<h1 id="renderers"><a class="toclink" href="#renderers">Renderers</a></h1>
|
|
<blockquote>
|
|
<p>Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.</p>
|
|
<p>— <a href="https://docs.djangoproject.com/en/stable/stable/template-response/#the-rendering-process">Django documentation</a></p>
|
|
</blockquote>
|
|
<p>REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.</p>
|
|
<h2 id="how-the-renderer-is-determined"><a class="toclink" href="#how-the-renderer-is-determined">How the renderer is determined</a></h2>
|
|
<p>The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.</p>
|
|
<p>The basic process of content negotiation involves examining the request's <code>Accept</code> header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL <code>http://example.com/api/users_count.json</code> might be an endpoint that always returns JSON data.</p>
|
|
<p>For more information see the documentation on <a href="../content-negotiation/">content negotiation</a>.</p>
|
|
<h2 id="setting-the-renderers"><a class="toclink" href="#setting-the-renderers">Setting the renderers</a></h2>
|
|
<p>The default set of renderers may be set globally, using the <code>DEFAULT_RENDERER_CLASSES</code> setting. For example, the following settings would use <code>JSON</code> as the main media type and also include the self describing API.</p>
|
|
<pre><code>REST_FRAMEWORK = {
|
|
'DEFAULT_RENDERER_CLASSES': (
|
|
'rest_framework.renderers.JSONRenderer',
|
|
'rest_framework.renderers.BrowsableAPIRenderer',
|
|
)
|
|
}
|
|
</code></pre>
|
|
<p>You can also set the renderers used for an individual view, or viewset,
|
|
using the <code>APIView</code> class-based views.</p>
|
|
<pre><code>from django.contrib.auth.models import User
|
|
from rest_framework.renderers import JSONRenderer
|
|
from rest_framework.response import Response
|
|
from rest_framework.views import APIView
|
|
|
|
class UserCountView(APIView):
|
|
"""
|
|
A view that returns the count of active users in JSON.
|
|
"""
|
|
renderer_classes = (JSONRenderer, )
|
|
|
|
def get(self, request, format=None):
|
|
user_count = User.objects.filter(active=True).count()
|
|
content = {'user_count': user_count}
|
|
return Response(content)
|
|
</code></pre>
|
|
<p>Or, if you're using the <code>@api_view</code> decorator with function based views.</p>
|
|
<pre><code>@api_view(['GET'])
|
|
@renderer_classes((JSONRenderer,))
|
|
def user_count_view(request, format=None):
|
|
"""
|
|
A view that returns the count of active users in JSON.
|
|
"""
|
|
user_count = User.objects.filter(active=True).count()
|
|
content = {'user_count': user_count}
|
|
return Response(content)
|
|
</code></pre>
|
|
<h2 id="ordering-of-renderer-classes"><a class="toclink" href="#ordering-of-renderer-classes">Ordering of renderer classes</a></h2>
|
|
<p>It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an <code>Accept: */*</code> header, or not including an <code>Accept</code> header at all, then REST framework will select the first renderer in the list to use for the response.</p>
|
|
<p>For example if your API serves JSON responses and the HTML browsable API, you might want to make <code>JSONRenderer</code> your default renderer, in order to send <code>JSON</code> responses to clients that do not specify an <code>Accept</code> header.</p>
|
|
<p>If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making <code>TemplateHTMLRenderer</code> your default renderer, in order to play nicely with older browsers that send <a href="http://www.gethifi.com/blog/browser-rest-http-accept-headers">broken accept headers</a>.</p>
|
|
<hr />
|
|
<h1 id="api-reference"><a class="toclink" href="#api-reference">API Reference</a></h1>
|
|
<h2 id="jsonrenderer"><a class="toclink" href="#jsonrenderer">JSONRenderer</a></h2>
|
|
<p>Renders the request data into <code>JSON</code>, using utf-8 encoding.</p>
|
|
<p>Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:</p>
|
|
<pre><code>{"unicode black star":"★","value":999}
|
|
</code></pre>
|
|
<p>The client may additionally include an <code>'indent'</code> media type parameter, in which case the returned <code>JSON</code> will be indented. For example <code>Accept: application/json; indent=4</code>.</p>
|
|
<pre><code>{
|
|
"unicode black star": "★",
|
|
"value": 999
|
|
}
|
|
</code></pre>
|
|
<p>The default JSON encoding style can be altered using the <code>UNICODE_JSON</code> and <code>COMPACT_JSON</code> settings keys.</p>
|
|
<p><strong>.media_type</strong>: <code>application/json</code></p>
|
|
<p><strong>.format</strong>: <code>'.json'</code></p>
|
|
<p><strong>.charset</strong>: <code>None</code></p>
|
|
<h2 id="templatehtmlrenderer"><a class="toclink" href="#templatehtmlrenderer">TemplateHTMLRenderer</a></h2>
|
|
<p>Renders data to HTML, using Django's standard template rendering.
|
|
Unlike other renderers, the data passed to the <code>Response</code> does not need to be serialized. Also, unlike other renderers, you may want to include a <code>template_name</code> argument when creating the <code>Response</code>.</p>
|
|
<p>The TemplateHTMLRenderer will create a <code>RequestContext</code>, using the <code>response.data</code> as the context dict, and determine a template name to use to render the context.</p>
|
|
<p>The template name is determined by (in order of preference):</p>
|
|
<ol>
|
|
<li>An explicit <code>template_name</code> argument passed to the response.</li>
|
|
<li>An explicit <code>.template_name</code> attribute set on this class.</li>
|
|
<li>The return result of calling <code>view.get_template_names()</code>.</li>
|
|
</ol>
|
|
<p>An example of a view that uses <code>TemplateHTMLRenderer</code>:</p>
|
|
<pre><code>class UserDetail(generics.RetrieveAPIView):
|
|
"""
|
|
A view that returns a templated HTML representation of a given user.
|
|
"""
|
|
queryset = User.objects.all()
|
|
renderer_classes = (TemplateHTMLRenderer,)
|
|
|
|
def get(self, request, *args, **kwargs):
|
|
self.object = self.get_object()
|
|
return Response({'user': self.object}, template_name='user_detail.html')
|
|
</code></pre>
|
|
<p>You can use <code>TemplateHTMLRenderer</code> either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.</p>
|
|
<p>If you're building websites that use <code>TemplateHTMLRenderer</code> along with other renderer classes, you should consider listing <code>TemplateHTMLRenderer</code> as the first class in the <code>renderer_classes</code> list, so that it will be prioritised first even for browsers that send poorly formed <code>ACCEPT:</code> headers.</p>
|
|
<p>See the <a href="../../topics/html-and-forms/"><em>HTML & Forms</em> Topic Page</a> for further examples of <code>TemplateHTMLRenderer</code> usage.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.html'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p>See also: <code>StaticHTMLRenderer</code></p>
|
|
<h2 id="statichtmlrenderer"><a class="toclink" href="#statichtmlrenderer">StaticHTMLRenderer</a></h2>
|
|
<p>A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.</p>
|
|
<p>An example of a view that uses <code>StaticHTMLRenderer</code>:</p>
|
|
<pre><code>@api_view(('GET',))
|
|
@renderer_classes((StaticHTMLRenderer,))
|
|
def simple_html_view(request):
|
|
data = '<html><body><h1>Hello, world</h1></body></html>'
|
|
return Response(data)
|
|
</code></pre>
|
|
<p>You can use <code>StaticHTMLRenderer</code> either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.html'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p>See also: <code>TemplateHTMLRenderer</code></p>
|
|
<h2 id="browsableapirenderer"><a class="toclink" href="#browsableapirenderer">BrowsableAPIRenderer</a></h2>
|
|
<p>Renders data into HTML for the Browsable API:</p>
|
|
<p><img alt="The BrowsableAPIRenderer" src="../../img/quickstart.png" /></p>
|
|
<p>This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.api'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p><strong>.template</strong>: <code>'rest_framework/api.html'</code></p>
|
|
<h4 id="customizing-browsableapirenderer"><a class="toclink" href="#customizing-browsableapirenderer">Customizing BrowsableAPIRenderer</a></h4>
|
|
<p>By default the response content will be rendered with the highest priority renderer apart from <code>BrowsableAPIRenderer</code>. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the <code>get_default_renderer()</code> method. For example:</p>
|
|
<pre><code>class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
|
|
def get_default_renderer(self, view):
|
|
return JSONRenderer()
|
|
</code></pre>
|
|
<h2 id="adminrenderer"><a class="toclink" href="#adminrenderer">AdminRenderer</a></h2>
|
|
<p>Renders data into HTML for an admin-like display:</p>
|
|
<p><img alt="The AdminRender view" src="../../img/admin.png" /></p>
|
|
<p>This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.</p>
|
|
<p>Note that views that have nested or list serializers for their input won't work well with the <code>AdminRenderer</code>, as the HTML forms are unable to properly support them.</p>
|
|
<p><strong>Note</strong>: The <code>AdminRenderer</code> is only able to include links to detail pages when a properly configured <code>URL_FIELD_NAME</code> (<code>url</code> by default) attribute is present in the data. For <code>HyperlinkedModelSerializer</code> this will be the case, but for <code>ModelSerializer</code> or plain <code>Serializer</code> classes you'll need to make sure to include the field explicitly. For example here we use models <code>get_absolute_url</code> method:</p>
|
|
<pre><code>class AccountSerializer(serializers.ModelSerializer):
|
|
url = serializers.CharField(source='get_absolute_url', read_only=True)
|
|
|
|
class Meta:
|
|
model = Account
|
|
</code></pre>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.admin'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p><strong>.template</strong>: <code>'rest_framework/admin.html'</code></p>
|
|
<h2 id="htmlformrenderer"><a class="toclink" href="#htmlformrenderer">HTMLFormRenderer</a></h2>
|
|
<p>Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <code><form></code> tags, a hidden CSRF input or any submit buttons.</p>
|
|
<p>This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the <code>render_form</code> template tag.</p>
|
|
<pre><code>{% load rest_framework %}
|
|
|
|
<form action="/submit-report/" method="post">
|
|
{% csrf_token %}
|
|
{% render_form serializer %}
|
|
<input type="submit" value="Save" />
|
|
</form>
|
|
</code></pre>
|
|
<p>For more information see the <a href="../../topics/html-and-forms/">HTML & Forms</a> documentation.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.form'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p><strong>.template</strong>: <code>'rest_framework/horizontal/form.html'</code></p>
|
|
<h2 id="multipartrenderer"><a class="toclink" href="#multipartrenderer">MultiPartRenderer</a></h2>
|
|
<p>This renderer is used for rendering HTML multipart form data. <strong>It is not suitable as a response renderer</strong>, but is instead used for creating test requests, using REST framework's <a href="../testing/">test client and test request factory</a>.</p>
|
|
<p><strong>.media_type</strong>: <code>multipart/form-data; boundary=BoUnDaRyStRiNg</code></p>
|
|
<p><strong>.format</strong>: <code>'.multipart'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<hr />
|
|
<h1 id="custom-renderers"><a class="toclink" href="#custom-renderers">Custom renderers</a></h1>
|
|
<p>To implement a custom renderer, you should override <code>BaseRenderer</code>, set the <code>.media_type</code> and <code>.format</code> properties, and implement the <code>.render(self, data, media_type=None, renderer_context=None)</code> method.</p>
|
|
<p>The method should return a bytestring, which will be used as the body of the HTTP response.</p>
|
|
<p>The arguments passed to the <code>.render()</code> method are:</p>
|
|
<h3 id="data"><a class="toclink" href="#data"><code>data</code></a></h3>
|
|
<p>The request data, as set by the <code>Response()</code> instantiation.</p>
|
|
<h3 id="media_typenone"><a class="toclink" href="#media_typenone"><code>media_type=None</code></a></h3>
|
|
<p>Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.</p>
|
|
<p>Depending on the client's <code>Accept:</code> header, this may be more specific than the renderer's <code>media_type</code> attribute, and may include media type parameters. For example <code>"application/json; nested=true"</code>.</p>
|
|
<h3 id="renderer_contextnone"><a class="toclink" href="#renderer_contextnone"><code>renderer_context=None</code></a></h3>
|
|
<p>Optional. If provided, this is a dictionary of contextual information provided by the view.</p>
|
|
<p>By default this will include the following keys: <code>view</code>, <code>request</code>, <code>response</code>, <code>args</code>, <code>kwargs</code>.</p>
|
|
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
|
|
<p>The following is an example plaintext renderer that will return a response with the <code>data</code> parameter as the content of the response.</p>
|
|
<pre><code>from django.utils.encoding import smart_unicode
|
|
from rest_framework import renderers
|
|
|
|
|
|
class PlainTextRenderer(renderers.BaseRenderer):
|
|
media_type = 'text/plain'
|
|
format = 'txt'
|
|
|
|
def render(self, data, media_type=None, renderer_context=None):
|
|
return data.encode(self.charset)
|
|
</code></pre>
|
|
<h2 id="setting-the-character-set"><a class="toclink" href="#setting-the-character-set">Setting the character set</a></h2>
|
|
<p>By default renderer classes are assumed to be using the <code>UTF-8</code> encoding. To use a different encoding, set the <code>charset</code> attribute on the renderer.</p>
|
|
<pre><code>class PlainTextRenderer(renderers.BaseRenderer):
|
|
media_type = 'text/plain'
|
|
format = 'txt'
|
|
charset = 'iso-8859-1'
|
|
|
|
def render(self, data, media_type=None, renderer_context=None):
|
|
return data.encode(self.charset)
|
|
</code></pre>
|
|
<p>Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the <code>Response</code> class, with the <code>charset</code> attribute set on the renderer used to determine the encoding.</p>
|
|
<p>If the renderer returns a bytestring representing raw binary content, you should set a charset value of <code>None</code>, which will ensure the <code>Content-Type</code> header of the response will not have a <code>charset</code> value set.</p>
|
|
<p>In some cases you may also want to set the <code>render_style</code> attribute to <code>'binary'</code>. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.</p>
|
|
<pre><code>class JPEGRenderer(renderers.BaseRenderer):
|
|
media_type = 'image/jpeg'
|
|
format = 'jpg'
|
|
charset = None
|
|
render_style = 'binary'
|
|
|
|
def render(self, data, media_type=None, renderer_context=None):
|
|
return data
|
|
</code></pre>
|
|
<hr />
|
|
<h1 id="advanced-renderer-usage"><a class="toclink" href="#advanced-renderer-usage">Advanced renderer usage</a></h1>
|
|
<p>You can do some pretty flexible things using REST framework's renderers. Some examples...</p>
|
|
<ul>
|
|
<li>Provide either flat or nested representations from the same endpoint, depending on the requested media type.</li>
|
|
<li>Serve both regular HTML webpages, and JSON based API responses from the same endpoints.</li>
|
|
<li>Specify multiple types of HTML representation for API clients to use.</li>
|
|
<li>Underspecify a renderer's media type, such as using <code>media_type = 'image/*'</code>, and use the <code>Accept</code> header to vary the encoding of the response.</li>
|
|
</ul>
|
|
<h2 id="varying-behaviour-by-media-type"><a class="toclink" href="#varying-behaviour-by-media-type">Varying behaviour by media type</a></h2>
|
|
<p>In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access <code>request.accepted_renderer</code> to determine the negotiated renderer that will be used for the response.</p>
|
|
<p>For example:</p>
|
|
<pre><code>@api_view(('GET',))
|
|
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
|
|
def list_users(request):
|
|
"""
|
|
A view that can return JSON or HTML representations
|
|
of the users in the system.
|
|
"""
|
|
queryset = Users.objects.filter(active=True)
|
|
|
|
if request.accepted_renderer.format == 'html':
|
|
# TemplateHTMLRenderer takes a context dict,
|
|
# and additionally requires a 'template_name'.
|
|
# It does not require serialization.
|
|
data = {'users': queryset}
|
|
return Response(data, template_name='list_users.html')
|
|
|
|
# JSONRenderer requires serialized data as normal.
|
|
serializer = UserSerializer(instance=queryset)
|
|
data = serializer.data
|
|
return Response(data)
|
|
</code></pre>
|
|
<h2 id="underspecifying-the-media-type"><a class="toclink" href="#underspecifying-the-media-type">Underspecifying the media type</a></h2>
|
|
<p>In some cases you might want a renderer to serve a range of media types.
|
|
In this case you can underspecify the media types it should respond to, by using a <code>media_type</code> value such as <code>image/*</code>, or <code>*/*</code>.</p>
|
|
<p>If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the <code>content_type</code> attribute. For example:</p>
|
|
<pre><code>return Response(data, content_type='image/png')
|
|
</code></pre>
|
|
<h2 id="designing-your-media-types"><a class="toclink" href="#designing-your-media-types">Designing your media types</a></h2>
|
|
<p>For the purposes of many Web APIs, simple <code>JSON</code> responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and <a href="http://timelessrepo.com/haters-gonna-hateoas">HATEOAS</a> you'll need to consider the design and usage of your media types in more detail.</p>
|
|
<p>In <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">the words of Roy Fielding</a>, "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".</p>
|
|
<p>For good examples of custom media types, see GitHub's use of a custom <a href="http://developer.github.com/v3/media/">application/vnd.github+json</a> media type, and Mike Amundsen's IANA approved <a href="http://www.amundsen.com/media-types/collection/">application/vnd.collection+json</a> JSON-based hypermedia.</p>
|
|
<h2 id="html-error-views"><a class="toclink" href="#html-error-views">HTML error views</a></h2>
|
|
<p>Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an <code>Http404</code> or <code>PermissionDenied</code> exception, or a subclass of <code>APIException</code>.</p>
|
|
<p>If you're using either the <code>TemplateHTMLRenderer</code> or the <code>StaticHTMLRenderer</code> and an exception is raised, the behavior is slightly different, and mirrors <a href="https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views">Django's default handling of error views</a>.</p>
|
|
<p>Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.</p>
|
|
<ul>
|
|
<li>Load and render a template named <code>{status_code}.html</code>.</li>
|
|
<li>Load and render a template named <code>api_exception.html</code>.</li>
|
|
<li>Render the HTTP status code and text, for example "404 Not Found".</li>
|
|
</ul>
|
|
<p>Templates will render with a <code>RequestContext</code> which includes the <code>status_code</code> and <code>details</code> keys.</p>
|
|
<p><strong>Note</strong>: If <code>DEBUG=True</code>, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.</p>
|
|
<hr />
|
|
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
|
|
<p>The following third party packages are also available.</p>
|
|
<h2 id="yaml"><a class="toclink" href="#yaml">YAML</a></h2>
|
|
<p><a href="http://jpadilla.github.io/django-rest-framework-yaml/">REST framework YAML</a> provides <a href="http://www.yaml.org/">YAML</a> parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
|
|
<h4 id="installation-configuration"><a class="toclink" href="#installation-configuration">Installation & configuration</a></h4>
|
|
<p>Install using pip.</p>
|
|
<pre><code>$ pip install djangorestframework-yaml
|
|
</code></pre>
|
|
<p>Modify your REST framework settings.</p>
|
|
<pre><code>REST_FRAMEWORK = {
|
|
'DEFAULT_PARSER_CLASSES': (
|
|
'rest_framework_yaml.parsers.YAMLParser',
|
|
),
|
|
'DEFAULT_RENDERER_CLASSES': (
|
|
'rest_framework_yaml.renderers.YAMLRenderer',
|
|
),
|
|
}
|
|
</code></pre>
|
|
<h2 id="xml"><a class="toclink" href="#xml">XML</a></h2>
|
|
<p><a href="http://jpadilla.github.io/django-rest-framework-xml/">REST Framework XML</a> provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
|
|
<h4 id="installation-configuration_1"><a class="toclink" href="#installation-configuration_1">Installation & configuration</a></h4>
|
|
<p>Install using pip.</p>
|
|
<pre><code>$ pip install djangorestframework-xml
|
|
</code></pre>
|
|
<p>Modify your REST framework settings.</p>
|
|
<pre><code>REST_FRAMEWORK = {
|
|
'DEFAULT_PARSER_CLASSES': (
|
|
'rest_framework_xml.parsers.XMLParser',
|
|
),
|
|
'DEFAULT_RENDERER_CLASSES': (
|
|
'rest_framework_xml.renderers.XMLRenderer',
|
|
),
|
|
}
|
|
</code></pre>
|
|
<h2 id="jsonp"><a class="toclink" href="#jsonp">JSONP</a></h2>
|
|
<p><a href="http://jpadilla.github.io/django-rest-framework-jsonp/">REST framework JSONP</a> provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
|
|
<hr />
|
|
<p><strong>Warning</strong>: If you require cross-domain AJAX requests, you should generally be using the more modern approach of <a href="http://www.w3.org/TR/cors/">CORS</a> as an alternative to <code>JSONP</code>. See the <a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors/">CORS documentation</a> for more details.</p>
|
|
<p>The <code>jsonp</code> approach is essentially a browser hack, and is <a href="http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use">only appropriate for globally readable API endpoints</a>, where <code>GET</code> requests are unauthenticated and do not require any user permissions.</p>
|
|
<hr />
|
|
<h4 id="installation-configuration_2"><a class="toclink" href="#installation-configuration_2">Installation & configuration</a></h4>
|
|
<p>Install using pip.</p>
|
|
<pre><code>$ pip install djangorestframework-jsonp
|
|
</code></pre>
|
|
<p>Modify your REST framework settings.</p>
|
|
<pre><code>REST_FRAMEWORK = {
|
|
'DEFAULT_RENDERER_CLASSES': (
|
|
'rest_framework_jsonp.renderers.JSONPRenderer',
|
|
),
|
|
}
|
|
</code></pre>
|
|
<h2 id="messagepack"><a class="toclink" href="#messagepack">MessagePack</a></h2>
|
|
<p><a href="http://msgpack.org/">MessagePack</a> is a fast, efficient binary serialization format. <a href="https://github.com/juanriaza">Juan Riaza</a> maintains the <a href="https://github.com/juanriaza/django-rest-framework-msgpack">djangorestframework-msgpack</a> package which provides MessagePack renderer and parser support for REST framework.</p>
|
|
<h2 id="csv"><a class="toclink" href="#csv">CSV</a></h2>
|
|
<p>Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. <a href="https://github.com/mjumbewu">Mjumbe Poe</a> maintains the <a href="https://github.com/mjumbewu/django-rest-framework-csv">djangorestframework-csv</a> package which provides CSV renderer support for REST framework.</p>
|
|
<h2 id="ultrajson"><a class="toclink" href="#ultrajson">UltraJSON</a></h2>
|
|
<p><a href="https://github.com/esnme/ultrajson">UltraJSON</a> is an optimized C JSON encoder which can give significantly faster JSON rendering. <a href="https://github.com/hzy">Jacob Haslehurst</a> maintains the <a href="https://github.com/gizmag/drf-ujson-renderer">drf-ujson-renderer</a> package which implements JSON rendering using the UJSON package.</p>
|
|
<h2 id="camelcase-json"><a class="toclink" href="#camelcase-json">CamelCase JSON</a></h2>
|
|
<p><a href="https://github.com/vbabiy/djangorestframework-camel-case">djangorestframework-camel-case</a> provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by <a href="https://github.com/vbabiy">Vitaly Babiy</a>.</p>
|
|
<h2 id="pandas-csv-excel-png"><a class="toclink" href="#pandas-csv-excel-png">Pandas (CSV, Excel, PNG)</a></h2>
|
|
<p><a href="https://github.com/wq/django-rest-pandas">Django REST Pandas</a> provides a serializer and renderers that support additional data processing and output via the <a href="http://pandas.pydata.org/">Pandas</a> DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both <code>.xls</code> and <code>.xlsx</code>), and a number of <a href="https://github.com/wq/django-rest-pandas#supported-formats">other formats</a>. It is maintained by <a href="https://github.com/sheppard">S. Andrew Sheppard</a> as part of the <a href="https://github.com/wq">wq Project</a>.</p>
|
|
<h2 id="latex"><a class="toclink" href="#latex">LaTeX</a></h2>
|
|
<p><a href="https://github.com/mypebble/rest-framework-latex">Rest Framework Latex</a> provides a renderer that outputs PDFs using Laulatex. It is maintained by <a href="https://github.com/mypebble">Pebble (S/F Software)</a>.</p>
|
|
|
|
|
|
</div> <!--/span-->
|
|
</div> <!--/row-->
|
|
</div> <!--/.fluid-container-->
|
|
</div> <!--/.body content-->
|
|
<div id="push"></div>
|
|
</div> <!--/.wrapper -->
|
|
|
|
<footer class="span12">
|
|
<p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.
|
|
</p>
|
|
</footer>
|
|
|
|
<!-- Le javascript
|
|
================================================== -->
|
|
<!-- Placed at the end of the document so the pages load faster -->
|
|
<script src="../../js/jquery-1.8.1-min.js"></script>
|
|
<script src="../../js/prettify-1.0.js"></script>
|
|
<script src="../../js/bootstrap-2.1.1-min.js"></script>
|
|
<script src="https://fund.django-rest-framework.org/sidebar_include.js"></script>
|
|
<script>var base_url = '../..';</script>
|
|
<script src="../../mkdocs/js/require.js"></script>
|
|
<script src="../../js/theme.js"></script>
|
|
|
|
<script>
|
|
var shiftWindow = function() {
|
|
scrollBy(0, -50)
|
|
};
|
|
|
|
if (location.hash) shiftWindow();
|
|
window.addEventListener("hashchange", shiftWindow);
|
|
|
|
$('.dropdown-menu').on('click touchstart', function(event) {
|
|
event.stopPropagation();
|
|
});
|
|
|
|
// Dynamically force sidenav/dropdown to no higher than browser window
|
|
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
|
|
|
|
$(function() {
|
|
$(window).resize(function() {
|
|
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
|
|
});
|
|
});
|
|
</script>
|
|
</body>
|
|
|
|
</html> |