gh-pages hosted docs
533
api-guide/authentication.html
Normal file
|
@ -0,0 +1,533 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Authentication</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Authentication, API Reference, Custom authentication, Third party packages">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="authentication-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 " href="../api-guide/permissions.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/relations.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#authentication">Authentication</a></li>
|
||||||
|
<li><a href="#how-authentication-is-determined">How authentication is determined</a></li>
|
||||||
|
<li><a href="#setting-the-authentication-scheme">Setting the authentication scheme</a></li>
|
||||||
|
<li><a href="#unauthorized-and-forbidden-responses">Unauthorized and Forbidden responses</a></li>
|
||||||
|
<li><a href="#apache-mod_wsgi-specific-configuration">Apache mod_wsgi specific configuration</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#basicauthentication">BasicAuthentication</a></li>
|
||||||
|
<li><a href="#tokenauthentication">TokenAuthentication</a></li>
|
||||||
|
<li><a href="#sessionauthentication">SessionAuthentication</a></li>
|
||||||
|
<li><a href="#oauthauthentication">OAuthAuthentication</a></li>
|
||||||
|
<li><a href="#oauth2authentication">OAuth2Authentication</a></li>
|
||||||
|
<li class="main"><a href="#custom-authentication">Custom authentication</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li class="main"><a href="#third-party-packages">Third party packages</a></li>
|
||||||
|
<li><a href="#digest-authentication">Digest Authentication</a></li>
|
||||||
|
<li><a href="#django-oauth-toolkit">Django OAuth Toolkit</a></li>
|
||||||
|
<li><a href="#django-oauth2-consumer">Django OAuth2 Consumer</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/authentication.py"><span class="label label-info">authentication.py</span></a></p>
|
||||||
|
<h1 id="authentication">Authentication</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Auth needs to be pluggable.</p>
|
||||||
|
<p>— Jacob Kaplan-Moss, <a href="http://jacobian.org/writing/rest-worst-practices/">"REST worst practices"</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The <a href="permissions.html">permission</a> and <a href="throttling.html">throttling</a> policies can then use those credentials to determine if the request should be permitted.</p>
|
||||||
|
<p>REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.</p>
|
||||||
|
<p>Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.</p>
|
||||||
|
<p>The <code>request.user</code> property will typically be set to an instance of the <code>contrib.auth</code> package's <code>User</code> class.</p>
|
||||||
|
<p>The <code>request.auth</code> property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note:</strong> Don't forget that <strong>authentication by itself won't allow or disallow an incoming request</strong>, it simply identifies the credentials that the request was made with.</p>
|
||||||
|
<p>For information on how to setup the permission polices for your API please see the <a href="permissions.html">permissions documentation</a>.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="how-authentication-is-determined">How authentication is determined</h2>
|
||||||
|
<p>The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set <code>request.user</code> and <code>request.auth</code> using the return value of the first class that successfully authenticates.</p>
|
||||||
|
<p>If no class authenticates, <code>request.user</code> will be set to an instance of <code>django.contrib.auth.models.AnonymousUser</code>, and <code>request.auth</code> will be set to <code>None</code>.</p>
|
||||||
|
<p>The value of <code>request.user</code> and <code>request.auth</code> for unauthenticated requests can be modified using the <code>UNAUTHENTICATED_USER</code> and <code>UNAUTHENTICATED_TOKEN</code> settings.</p>
|
||||||
|
<h2 id="setting-the-authentication-scheme">Setting the authentication scheme</h2>
|
||||||
|
<p>The default authentication schemes may be set globally, using the <code>DEFAULT_AUTHENTICATION</code> setting. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||||
|
'rest_framework.authentication.BasicAuthentication',
|
||||||
|
'rest_framework.authentication.SessionAuthentication',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also set the authentication scheme on a per-view or per-viewset basis,
|
||||||
|
using the <code>APIView</code> class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.authentication import SessionAuthentication, BasicAuthentication
|
||||||
|
from rest_framework.permissions import IsAuthenticated
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
class ExampleView(APIView):
|
||||||
|
authentication_classes = (SessionAuthentication, BasicAuthentication)
|
||||||
|
permission_classes = (IsAuthenticated,)
|
||||||
|
|
||||||
|
def get(self, request, format=None):
|
||||||
|
content = {
|
||||||
|
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||||
|
'auth': unicode(request.auth), # None
|
||||||
|
}
|
||||||
|
return Response(content)
|
||||||
|
</code></pre>
|
||||||
|
<p>Or, if you're using the <code>@api_view</code> decorator with function based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@api_view(['GET'])
|
||||||
|
@authentication_classes((SessionAuthentication, BasicAuthentication))
|
||||||
|
@permission_classes((IsAuthenticated,))
|
||||||
|
def example_view(request, format=None):
|
||||||
|
content = {
|
||||||
|
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||||
|
'auth': unicode(request.auth), # None
|
||||||
|
}
|
||||||
|
return Response(content)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="unauthorized-and-forbidden-responses">Unauthorized and Forbidden responses</h2>
|
||||||
|
<p>When an unauthenticated request is denied permission there are two different error codes that may be appropriate.</p>
|
||||||
|
<ul>
|
||||||
|
<li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2">HTTP 401 Unauthorized</a></li>
|
||||||
|
<li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4">HTTP 403 Permission Denied</a></li>
|
||||||
|
</ul>
|
||||||
|
<p>HTTP 401 responses must always include a <code>WWW-Authenticate</code> header, that instructs the client how to authenticate. HTTP 403 responses do not include the <code>WWW-Authenticate</code> header.</p>
|
||||||
|
<p>The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. <strong>The first authentication class set on the view is used when determining the type of response</strong>.</p>
|
||||||
|
<p>Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a <code>403 Permission Denied</code> response will always be used, regardless of the authentication scheme.</p>
|
||||||
|
<h2 id="apache-mod_wsgi-specific-configuration">Apache mod_wsgi specific configuration</h2>
|
||||||
|
<p>Note that if deploying to <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization">Apache using mod_wsgi</a>, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.</p>
|
||||||
|
<p>If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the <code>WSGIPassAuthorization</code> directive in the appropriate context and setting it to <code>'On'</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># this can go in either server config, virtual host, directory or .htaccess
|
||||||
|
WSGIPassAuthorization On
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="basicauthentication">BasicAuthentication</h2>
|
||||||
|
<p>This authentication scheme uses <a href="http://tools.ietf.org/html/rfc2617">HTTP Basic Authentication</a>, signed against a user's username and password. Basic authentication is generally only appropriate for testing.</p>
|
||||||
|
<p>If successfully authenticated, <code>BasicAuthentication</code> provides the following credentials.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>request.user</code> will be a Django <code>User</code> instance.</li>
|
||||||
|
<li><code>request.auth</code> will be <code>None</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Unauthenticated responses that are denied permission will result in an <code>HTTP 401 Unauthorized</code> response with an appropriate WWW-Authenticate header. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>WWW-Authenticate: Basic realm="api"
|
||||||
|
</code></pre>
|
||||||
|
<p><strong>Note:</strong> If you use <code>BasicAuthentication</code> in production you must ensure that your API is only available over <code>https</code>. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.</p>
|
||||||
|
<h2 id="tokenauthentication">TokenAuthentication</h2>
|
||||||
|
<p>This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. </p>
|
||||||
|
<p>To use the <code>TokenAuthentication</code> scheme, include <code>rest_framework.authtoken</code> in your <code>INSTALLED_APPS</code> setting:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>INSTALLED_APPS = (
|
||||||
|
...
|
||||||
|
'rest_framework.authtoken'
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Make sure to run <code>manage.py syncdb</code> after changing your settings. The <code>authtoken</code> database tables are managed by south (see <a href="#schema-migrations">Schema migrations</a> below).</p>
|
||||||
|
<p>You'll also need to create tokens for your users.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.authtoken.models import Token
|
||||||
|
|
||||||
|
token = Token.objects.create(user=...)
|
||||||
|
print token.key
|
||||||
|
</code></pre>
|
||||||
|
<p>For clients to authenticate, the token key should be included in the <code>Authorization</code> HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
|
||||||
|
</code></pre>
|
||||||
|
<p>If successfully authenticated, <code>TokenAuthentication</code> provides the following credentials.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>request.user</code> will be a Django <code>User</code> instance.</li>
|
||||||
|
<li><code>request.auth</code> will be a <code>rest_framework.authtoken.models.BasicToken</code> instance.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Unauthenticated responses that are denied permission will result in an <code>HTTP 401 Unauthorized</code> response with an appropriate WWW-Authenticate header. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>WWW-Authenticate: Token
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>curl</code> command line tool may be useful for testing token authenticated APIs. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note:</strong> If you use <code>TokenAuthentication</code> in production you must ensure that your API is only available over <code>https</code>.</p>
|
||||||
|
<hr />
|
||||||
|
<h4 id="generating-tokens">Generating Tokens</h4>
|
||||||
|
<p>If you want every user to have an automatically generated Token, you can simply catch the User's <code>post_save</code> signal.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.dispatch import receiver
|
||||||
|
from rest_framework.authtoken.models import Token
|
||||||
|
|
||||||
|
@receiver(post_save, sender=User)
|
||||||
|
def create_auth_token(sender, instance=None, created=False, **kwargs):
|
||||||
|
if created:
|
||||||
|
Token.objects.create(user=instance)
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that you'll want to ensure you place this code snippet in an installed <code>models.py</code> module, or some other location that will be imported by Django on startup.</p>
|
||||||
|
<p>If you've already created some users, you can generate tokens for all existing users like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from rest_framework.authtoken.models import Token
|
||||||
|
|
||||||
|
for user in User.objects.all():
|
||||||
|
Token.objects.get_or_create(user=user)
|
||||||
|
</code></pre>
|
||||||
|
<p>When using <code>TokenAuthentication</code>, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the <code>obtain_auth_token</code> view to your URLconf:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>urlpatterns += patterns('',
|
||||||
|
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that the URL part of the pattern can be whatever you want to use.</p>
|
||||||
|
<p>The <code>obtain_auth_token</code> view will return a JSON response when valid <code>username</code> and <code>password</code> fields are POSTed to the view using form data or JSON:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that the default <code>obtain_auth_token</code> view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the <code>obtain_auth_token</code> view, you can do so by overriding the <code>ObtainAuthToken</code> view class, and using that in your url conf instead.</p>
|
||||||
|
<h4 id="schema-migrations">Schema migrations</h4>
|
||||||
|
<p>The <code>rest_framework.authtoken</code> app includes a south migration that will create the authtoken table.</p>
|
||||||
|
<p>If you're using a <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model">custom user model</a> you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.</p>
|
||||||
|
<p>You can do so by inserting a <code>needed_by</code> attribute in your user migration:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class Migration:
|
||||||
|
|
||||||
|
needed_by = (
|
||||||
|
('authtoken', '0001_initial'),
|
||||||
|
)
|
||||||
|
|
||||||
|
def forwards(self):
|
||||||
|
...
|
||||||
|
</code></pre>
|
||||||
|
<p>For more details, see the <a href="http://south.readthedocs.org/en/latest/dependencies.html">south documentation on dependencies</a>.</p>
|
||||||
|
<p>Also note that if you're using a <code>post_save</code> signal to create tokens, then the first time you create the database tables, you'll need to ensure any migrations are run prior to creating any superusers. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py syncdb --noinput # Won't create a superuser just yet, due to `--noinput`.
|
||||||
|
python manage.py migrate
|
||||||
|
python manage.py createsuperuser
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="sessionauthentication">SessionAuthentication</h2>
|
||||||
|
<p>This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.</p>
|
||||||
|
<p>If successfully authenticated, <code>SessionAuthentication</code> provides the following credentials.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>request.user</code> will be a Django <code>User</code> instance.</li>
|
||||||
|
<li><code>request.auth</code> will be <code>None</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Unauthenticated responses that are denied permission will result in an <code>HTTP 403 Forbidden</code> response.</p>
|
||||||
|
<p>If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as <code>PUT</code>, <code>PATCH</code>, <code>POST</code> or <code>DELETE</code> requests. See the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax">Django CSRF documentation</a> for more details.</p>
|
||||||
|
<h2 id="oauthauthentication">OAuthAuthentication</h2>
|
||||||
|
<p>This authentication uses <a href="http://oauth.net/core/1.0a">OAuth 1.0a</a> authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests.</p>
|
||||||
|
<p>This authentication class depends on the optional <code>django-oauth-plus</code> and <code>oauth2</code> packages. In order to make it work you must install these packages and add <code>oauth_provider</code> to your <code>INSTALLED_APPS</code>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>INSTALLED_APPS = (
|
||||||
|
...
|
||||||
|
`oauth_provider`,
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Don't forget to run <code>syncdb</code> once you've added the package.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py syncdb
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="getting-started-with-django-oauth-plus">Getting started with django-oauth-plus</h4>
|
||||||
|
<p>The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens.</p>
|
||||||
|
<p>The <code>django-oauth-plus</code> package provides simple foundation for classic 'three-legged' oauth flow. Please refer to <a href="http://code.larlet.fr/django-oauth-plus">the documentation</a> for more details.</p>
|
||||||
|
<h2 id="oauth2authentication">OAuth2Authentication</h2>
|
||||||
|
<p>This authentication uses <a href="http://tools.ietf.org/html/rfc6749">OAuth 2.0</a> authentication scheme. OAuth2 is more simple to work with than OAuth1, and provides much better security than simple token authentication. It is an unauthenticated scheme, and requires you to use an HTTPS connection.</p>
|
||||||
|
<p>This authentication class depends on the optional <a href="https://github.com/caffeinehit/django-oauth2-provider">django-oauth2-provider</a> project. In order to make it work you must install this package and add <code>provider</code> and <code>provider.oauth2</code> to your <code>INSTALLED_APPS</code>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>INSTALLED_APPS = (
|
||||||
|
...
|
||||||
|
'provider',
|
||||||
|
'provider.oauth2',
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Then add <code>OAuth2Authentication</code> to your global <code>DEFAULT_AUTHENTICATION</code> setting:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||||
|
'rest_framework.authentication.OAuth2Authentication',
|
||||||
|
),
|
||||||
|
</code></pre>
|
||||||
|
<p>You must also include the following in your root <code>urls.py</code> module:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that the <code>namespace='oauth2'</code> argument is required.</p>
|
||||||
|
<p>Finally, sync your database.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py syncdb
|
||||||
|
python manage.py migrate
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note:</strong> If you use <code>OAuth2Authentication</code> in production you must ensure that your API is only available over <code>https</code>.</p>
|
||||||
|
<hr />
|
||||||
|
<h4 id="getting-started-with-django-oauth2-provider">Getting started with django-oauth2-provider</h4>
|
||||||
|
<p>The <code>OAuth2Authentication</code> class only provides token verification for requests. It doesn't provide authorization flow for your clients.</p>
|
||||||
|
<p>The OAuth 2 authorization flow is taken care by the <a href="https://github.com/caffeinehit/django-oauth2-provider">django-oauth2-provider</a> dependency. A walkthrough is given here, but for more details you should refer to <a href="https://django-oauth2-provider.readthedocs.org/en/latest/">the documentation</a>.</p>
|
||||||
|
<p>To get started:</p>
|
||||||
|
<h5 id="1-create-a-client">1. Create a client</h5>
|
||||||
|
<p>You can create a client, either through the shell, or by using the Django admin.</p>
|
||||||
|
<p>Go to the admin panel and create a new <code>Provider.Client</code> entry. It will create the <code>client_id</code> and <code>client_secret</code> properties for you.</p>
|
||||||
|
<h5 id="2-request-an-access-token">2. Request an access token</h5>
|
||||||
|
<p>To request an access token, submit a <code>POST</code> request to the url <code>/oauth2/access_token</code> with the following fields:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>client_id</code> the client id you've just configured at the previous step.</li>
|
||||||
|
<li><code>client_secret</code> again configured at the previous step.</li>
|
||||||
|
<li><code>username</code> the username with which you want to log in.</li>
|
||||||
|
<li><code>password</code> well, that speaks for itself.</li>
|
||||||
|
</ul>
|
||||||
|
<p>You can use the command line to test that your local configuration is working:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/
|
||||||
|
</code></pre>
|
||||||
|
<p>You should get a response that looks something like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{"access_token": "<your-access-token>", "scope": "read", "expires_in": 86399, "refresh_token": "<your-refresh-token>"}
|
||||||
|
</code></pre>
|
||||||
|
<h5 id="3-access-the-api">3. Access the API</h5>
|
||||||
|
<p>The only thing needed to make the <code>OAuth2Authentication</code> class work is to insert the <code>access_token</code> you've received in the <code>Authorization</code> request header.</p>
|
||||||
|
<p>The command line to test the authentication looks like:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl -H "Authorization: Bearer <your-access-token>" http://localhost:8000/api/
|
||||||
|
</code></pre>
|
||||||
|
<h3 id="alternative-oauth-2-implementations">Alternative OAuth 2 implementations</h3>
|
||||||
|
<p>Note that <a href="https://github.com/evonove/django-oauth-toolkit">Django OAuth Toolkit</a> is an alternative external package that also includes OAuth 2.0 support for REST framework.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-authentication">Custom authentication</h1>
|
||||||
|
<p>To implement a custom authentication scheme, subclass <code>BaseAuthentication</code> and override the <code>.authenticate(self, request)</code> method. The method should return a two-tuple of <code>(user, auth)</code> if authentication succeeds, or <code>None</code> otherwise.</p>
|
||||||
|
<p>In some circumstances instead of returning <code>None</code>, you may want to raise an <code>AuthenticationFailed</code> exception from the <code>.authenticate()</code> method.</p>
|
||||||
|
<p>Typically the approach you should take is:</p>
|
||||||
|
<ul>
|
||||||
|
<li>If authentication is not attempted, return <code>None</code>. Any other authentication schemes also in use will still be checked.</li>
|
||||||
|
<li>If authentication is attempted but fails, raise a <code>AuthenticationFailed</code> exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.</li>
|
||||||
|
</ul>
|
||||||
|
<p>You <em>may</em> also override the <code>.authenticate_header(self, request)</code> method. If implemented, it should return a string that will be used as the value of the <code>WWW-Authenticate</code> header in a <code>HTTP 401 Unauthorized</code> response.</p>
|
||||||
|
<p>If the <code>.authenticate_header()</code> method is not overridden, the authentication scheme will return <code>HTTP 403 Forbidden</code> responses when an unauthenticated request is denied access.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from rest_framework import authentication
|
||||||
|
from rest_framework import exceptions
|
||||||
|
|
||||||
|
class ExampleAuthentication(authentication.BaseAuthentication):
|
||||||
|
def authenticate(self, request):
|
||||||
|
username = request.META.get('X_USERNAME')
|
||||||
|
if not username:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
user = User.objects.get(username=username)
|
||||||
|
except User.DoesNotExist:
|
||||||
|
raise exceptions.AuthenticationFailed('No such user')
|
||||||
|
|
||||||
|
return (user, None)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="third-party-packages">Third party packages</h1>
|
||||||
|
<p>The following third party packages are also available.</p>
|
||||||
|
<h2 id="digest-authentication">Digest Authentication</h2>
|
||||||
|
<p>HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. <a href="https://github.com/juanriaza">Juan Riaza</a> maintains the <a href="https://github.com/juanriaza/django-rest-framework-digestauth">djangorestframework-digestauth</a> package which provides HTTP digest authentication support for REST framework.</p>
|
||||||
|
<h2 id="django-oauth-toolkit">Django OAuth Toolkit</h2>
|
||||||
|
<p>The <a href="https://github.com/evonove/django-oauth-toolkit">Django OAuth Toolkit</a> package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by <a href="https://github.com/evonove/">Evonove</a> and uses the excelllent <a href="https://github.com/idan/oauthlib">OAuthLib</a>. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support.</p>
|
||||||
|
<h2 id="django-oauth2-consumer">Django OAuth2 Consumer</h2>
|
||||||
|
<p>The <a href="https://github.com/Rediker-Software/doac">Django OAuth2 Consumer</a> library from <a href="https://github.com/Rediker-Software">Rediker Software</a> is another package that provides <a href="https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md#">OAuth 2.0 support for REST framework</a>. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
315
api-guide/content-negotiation.html
Normal file
|
@ -0,0 +1,315 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Content negotiation</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Content negotiation, Custom content negotiation">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="content-negotiation-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 " href="../api-guide/format-suffixes.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/pagination.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#content-negotiation">Content negotiation</a></li>
|
||||||
|
<li><a href="#determining-the-accepted-renderer">Determining the accepted renderer</a></li>
|
||||||
|
<li class="main"><a href="#custom-content-negotiation">Custom content negotiation</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li><a href="#setting-the-content-negotiation">Setting the content negotiation</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/negotiation.py"><span class="label label-info">negotiation.py</span></a></p>
|
||||||
|
<h1 id="content-negotiation">Content negotiation</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.</p>
|
||||||
|
<p>— <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html">RFC 2616</a>, Fielding et al.</p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.</p>
|
||||||
|
<h2 id="determining-the-accepted-renderer">Determining the accepted renderer</h2>
|
||||||
|
<p>REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's <code>Accept:</code> header. The style used is partly client-driven, and partly server-driven.</p>
|
||||||
|
<ol>
|
||||||
|
<li>More specific media types are given preference to less specific media types.</li>
|
||||||
|
<li>If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view.</li>
|
||||||
|
</ol>
|
||||||
|
<p>For example, given the following <code>Accept</code> header:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>application/json; indent=4, application/json, application/yaml, text/html, */*
|
||||||
|
</code></pre>
|
||||||
|
<p>The priorities for each of the given media types would be:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>application/json; indent=4</code></li>
|
||||||
|
<li><code>application/json</code>, <code>application/yaml</code> and <code>text/html</code></li>
|
||||||
|
<li><code>*/*</code></li>
|
||||||
|
</ul>
|
||||||
|
<p>If the requested view was only configured with renderers for <code>YAML</code> and <code>HTML</code>, then REST framework would select whichever renderer was listed first in the <code>renderer_classes</code> list or <code>DEFAULT_RENDERER_CLASSES</code> setting.</p>
|
||||||
|
<p>For more information on the <code>HTTP Accept</code> header, see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC 2616</a> </p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note</strong>: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.</p>
|
||||||
|
<p>This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-content-negotiation">Custom content negotiation</h1>
|
||||||
|
<p>It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override <code>BaseContentNegotiation</code>.</p>
|
||||||
|
<p>REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the <code>.select_parser(request, parsers)</code> and <code>.select_renderer(request, renderers, format_suffix)</code> methods.</p>
|
||||||
|
<p>The <code>select_parser()</code> method should return one of the parser instances from the list of available parsers, or <code>None</code> if none of the parsers can handle the incoming request.</p>
|
||||||
|
<p>The <code>select_renderer()</code> method should return a two-tuple of (renderer instance, media type), or raise a <code>NotAcceptable</code> exception.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>The following is a custom content negotiation class which ignores the client
|
||||||
|
request when selecting the appropriate parser or renderer.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.negotiation import BaseContentNegotiation
|
||||||
|
|
||||||
|
class IgnoreClientContentNegotiation(BaseContentNegotiation):
|
||||||
|
def select_parser(self, request, parsers):
|
||||||
|
"""
|
||||||
|
Select the first parser in the `.parser_classes` list.
|
||||||
|
"""
|
||||||
|
return parsers[0]
|
||||||
|
|
||||||
|
def select_renderer(self, request, renderers, format_suffix):
|
||||||
|
"""
|
||||||
|
Select the first renderer in the `.renderer_classes` list.
|
||||||
|
"""
|
||||||
|
return (renderers[0], renderers[0].media_type)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="setting-the-content-negotiation">Setting the content negotiation</h2>
|
||||||
|
<p>The default content negotiation class may be set globally, using the <code>DEFAULT_CONTENT_NEGOTIATION_CLASS</code> setting. For example, the following settings would use our example <code>IgnoreClientContentNegotiation</code> class.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also set the content negotiation used for an individual view, or viewset, using the <code>APIView</code> class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from myapp.negotiation import IgnoreClientContentNegotiation
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
class NoNegotiationView(APIView):
|
||||||
|
"""
|
||||||
|
An example view that does not perform content negotiation.
|
||||||
|
"""
|
||||||
|
content_negotiation_class = IgnoreClientContentNegotiation
|
||||||
|
|
||||||
|
def get(self, request, format=None):
|
||||||
|
return Response({
|
||||||
|
'accepted media type': request.accepted_renderer.media_type
|
||||||
|
})
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
345
api-guide/exceptions.html
Normal file
|
@ -0,0 +1,345 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Exceptions</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Exceptions, API Reference">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="exceptions-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 " href="../api-guide/status-codes.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/reverse.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#exceptions">Exceptions</a></li>
|
||||||
|
<li><a href="#exception-handling-in-rest-framework-views">Exception handling in REST framework views</a></li>
|
||||||
|
<li><a href="#custom-exception-handling">Custom exception handling</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#apiexception">APIException</a></li>
|
||||||
|
<li><a href="#parseerror">ParseError</a></li>
|
||||||
|
<li><a href="#authenticationfailed">AuthenticationFailed</a></li>
|
||||||
|
<li><a href="#notauthenticated">NotAuthenticated</a></li>
|
||||||
|
<li><a href="#permissiondenied">PermissionDenied</a></li>
|
||||||
|
<li><a href="#methodnotallowed">MethodNotAllowed</a></li>
|
||||||
|
<li><a href="#unsupportedmediatype">UnsupportedMediaType</a></li>
|
||||||
|
<li><a href="#throttled">Throttled</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/exceptions.py"><span class="label label-info">exceptions.py</span></a></p>
|
||||||
|
<h1 id="exceptions">Exceptions</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.</p>
|
||||||
|
<p>— Doug Hellmann, <a href="http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html">Python Exception Handling Techniques</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<h2 id="exception-handling-in-rest-framework-views">Exception handling in REST framework views</h2>
|
||||||
|
<p>REST framework's views handle various exceptions, and deal with returning appropriate error responses.</p>
|
||||||
|
<p>The handled exceptions are:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Subclasses of <code>APIException</code> raised inside REST framework.</li>
|
||||||
|
<li>Django's <code>Http404</code> exception.</li>
|
||||||
|
<li>Django's <code>PermissionDenied</code> exception.</li>
|
||||||
|
</ul>
|
||||||
|
<p>In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.</p>
|
||||||
|
<p>By default all error responses will include a key <code>details</code> in the body of the response, but other keys may also be included.</p>
|
||||||
|
<p>For example, the following request:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>DELETE http://api.example.com/foo/bar HTTP/1.1
|
||||||
|
Accept: application/json
|
||||||
|
</code></pre>
|
||||||
|
<p>Might receive an error response indicating that the <code>DELETE</code> method is not allowed on that resource:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>HTTP/1.1 405 Method Not Allowed
|
||||||
|
Content-Type: application/json
|
||||||
|
Content-Length: 42
|
||||||
|
|
||||||
|
{"detail": "Method 'DELETE' not allowed."}
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="custom-exception-handling">Custom exception handling</h2>
|
||||||
|
<p>You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.</p>
|
||||||
|
<p>The function must take a single argument, which is the exception to be handled, and should either return a <code>Response</code> object, or return <code>None</code> if the exception cannot be handled. If the handler returns <code>None</code> then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.</p>
|
||||||
|
<p>For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>HTTP/1.1 405 Method Not Allowed
|
||||||
|
Content-Type: application/json
|
||||||
|
Content-Length: 62
|
||||||
|
|
||||||
|
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
|
||||||
|
</code></pre>
|
||||||
|
<p>In order to alter the style of the response, you could write the following custom exception handler:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.views import exception_handler
|
||||||
|
|
||||||
|
def custom_exception_handler(exc):
|
||||||
|
# Call REST framework's default exception handler first,
|
||||||
|
# to get the standard error response.
|
||||||
|
response = exception_handler(exc)
|
||||||
|
|
||||||
|
# Now add the HTTP status code to the response.
|
||||||
|
if response is not None:
|
||||||
|
response.data['status_code'] = response.status_code
|
||||||
|
|
||||||
|
return response
|
||||||
|
</code></pre>
|
||||||
|
<p>The exception handler must also be configured in your settings, using the <code>EXCEPTION_HANDLER</code> setting key. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>If not specified, the <code>'EXCEPTION_HANDLER'</code> setting defaults to the standard exception handler provided by REST framework:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the <code>HTTP_400_BAD_REQUEST</code> responses that are returned by the generic views when serializer validation fails.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="apiexception">APIException</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>APIException()</code></p>
|
||||||
|
<p>The <strong>base class</strong> for all exceptions raised inside REST framework.</p>
|
||||||
|
<p>To provide a custom exception, subclass <code>APIException</code> and set the <code>.status_code</code> and <code>.detail</code> properties on the class.</p>
|
||||||
|
<h2 id="parseerror">ParseError</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>ParseError(detail=None)</code></p>
|
||||||
|
<p>Raised if the request contains malformed data when accessing <code>request.DATA</code> or <code>request.FILES</code>.</p>
|
||||||
|
<p>By default this exception results in a response with the HTTP status code "400 Bad Request".</p>
|
||||||
|
<h2 id="authenticationfailed">AuthenticationFailed</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>AuthenticationFailed(detail=None)</code></p>
|
||||||
|
<p>Raised when an incoming request includes incorrect authentication.</p>
|
||||||
|
<p>By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the <a href="authentication.html">authentication documentation</a> for more details.</p>
|
||||||
|
<h2 id="notauthenticated">NotAuthenticated</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>NotAuthenticated(detail=None)</code></p>
|
||||||
|
<p>Raised when an unauthenticated request fails the permission checks.</p>
|
||||||
|
<p>By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the <a href="authentication.html">authentication documentation</a> for more details.</p>
|
||||||
|
<h2 id="permissiondenied">PermissionDenied</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>PermissionDenied(detail=None)</code></p>
|
||||||
|
<p>Raised when an authenticated request fails the permission checks.</p>
|
||||||
|
<p>By default this exception results in a response with the HTTP status code "403 Forbidden".</p>
|
||||||
|
<h2 id="methodnotallowed">MethodNotAllowed</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>MethodNotAllowed(method, detail=None)</code></p>
|
||||||
|
<p>Raised when an incoming request occurs that does not map to a handler method on the view.</p>
|
||||||
|
<p>By default this exception results in a response with the HTTP status code "405 Method Not Allowed".</p>
|
||||||
|
<h2 id="unsupportedmediatype">UnsupportedMediaType</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>UnsupportedMediaType(media_type, detail=None)</code></p>
|
||||||
|
<p>Raised if there are no parsers that can handle the content type of the request data when accessing <code>request.DATA</code> or <code>request.FILES</code>.</p>
|
||||||
|
<p>By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".</p>
|
||||||
|
<h2 id="throttled">Throttled</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>Throttled(wait=None, detail=None)</code></p>
|
||||||
|
<p>Raised when an incoming request fails the throttling checks.</p>
|
||||||
|
<p>By default this exception results in a response with the HTTP status code "429 Too Many Requests".</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
487
api-guide/fields.html
Normal file
|
@ -0,0 +1,487 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Serializer fields</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Serializer fields, Generic Fields, Typed Fields, Custom fields">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="fields-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 " href="../api-guide/relations.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/serializers.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#serializer-fields">Serializer fields</a></li>
|
||||||
|
<li><a href="#core-arguments">Core arguments</a></li>
|
||||||
|
<li class="main"><a href="#generic-fields">Generic Fields</a></li>
|
||||||
|
<li><a href="#field">Field</a></li>
|
||||||
|
<li><a href="#writablefield">WritableField</a></li>
|
||||||
|
<li><a href="#modelfield">ModelField</a></li>
|
||||||
|
<li><a href="#serializermethodfield">SerializerMethodField</a></li>
|
||||||
|
<li class="main"><a href="#typed-fields">Typed Fields</a></li>
|
||||||
|
<li><a href="#booleanfield">BooleanField</a></li>
|
||||||
|
<li><a href="#charfield">CharField</a></li>
|
||||||
|
<li><a href="#urlfield">URLField</a></li>
|
||||||
|
<li><a href="#slugfield">SlugField</a></li>
|
||||||
|
<li><a href="#choicefield">ChoiceField</a></li>
|
||||||
|
<li><a href="#emailfield">EmailField</a></li>
|
||||||
|
<li><a href="#regexfield">RegexField</a></li>
|
||||||
|
<li><a href="#datetimefield">DateTimeField</a></li>
|
||||||
|
<li><a href="#datefield">DateField</a></li>
|
||||||
|
<li><a href="#timefield">TimeField</a></li>
|
||||||
|
<li><a href="#integerfield">IntegerField</a></li>
|
||||||
|
<li><a href="#floatfield">FloatField</a></li>
|
||||||
|
<li><a href="#decimalfield">DecimalField</a></li>
|
||||||
|
<li><a href="#filefield">FileField</a></li>
|
||||||
|
<li><a href="#imagefield">ImageField</a></li>
|
||||||
|
<li class="main"><a href="#custom-fields">Custom fields</a></li>
|
||||||
|
<li><a href="#examples">Examples</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/fields.py"><span class="label label-info">fields.py</span></a></p>
|
||||||
|
<h1 id="serializer-fields">Serializer fields</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format. </p>
|
||||||
|
<p>— <a href="https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data">Django documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note:</strong> The serializer fields are declared in fields.py, but by convention you should import them using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.<FieldName></code>.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="core-arguments">Core arguments</h2>
|
||||||
|
<p>Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:</p>
|
||||||
|
<h3 id="source"><code>source</code></h3>
|
||||||
|
<p>The name of the attribute that will be used to populate the field. May be a method that only takes a <code>self</code> argument, such as <code>Field(source='get_absolute_url')</code>, or may use dotted notation to traverse attributes, such as <code>Field(source='user.email')</code>.</p>
|
||||||
|
<p>The value <code>source='*'</code> has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations. (See the implementation of the <code>PaginationSerializer</code> class for an example.)</p>
|
||||||
|
<p>Defaults to the name of the field.</p>
|
||||||
|
<h3 id="read_only"><code>read_only</code></h3>
|
||||||
|
<p>Set this to <code>True</code> to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.</p>
|
||||||
|
<p>Defaults to <code>False</code></p>
|
||||||
|
<h3 id="required"><code>required</code></h3>
|
||||||
|
<p>Normally an error will be raised if a field is not supplied during deserialization.
|
||||||
|
Set to false if this field is not required to be present during deserialization.</p>
|
||||||
|
<p>Defaults to <code>True</code>.</p>
|
||||||
|
<h3 id="default"><code>default</code></h3>
|
||||||
|
<p>If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all. </p>
|
||||||
|
<p>May be set to a function or other callable, in which case the value will be evaluated each time it is used.</p>
|
||||||
|
<h3 id="validators"><code>validators</code></h3>
|
||||||
|
<p>A list of Django validators that should be used to validate deserialized values.</p>
|
||||||
|
<h3 id="error_messages"><code>error_messages</code></h3>
|
||||||
|
<p>A dictionary of error codes to error messages.</p>
|
||||||
|
<h3 id="widget"><code>widget</code></h3>
|
||||||
|
<p>Used only if rendering the field to HTML.
|
||||||
|
This argument sets the widget that should be used to render the field.</p>
|
||||||
|
<h3 id="label"><code>label</code></h3>
|
||||||
|
<p>A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.</p>
|
||||||
|
<h3 id="help_text"><code>help_text</code></h3>
|
||||||
|
<p>A text string that may be used as a description of the field in HTML form fields or other descriptive elements.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="generic-fields">Generic Fields</h1>
|
||||||
|
<p>These generic fields are used for representing arbitrary model fields or the output of model methods.</p>
|
||||||
|
<h2 id="field">Field</h2>
|
||||||
|
<p>A generic, <strong>read-only</strong> field. You can use this field for any attribute that does not need to support write operations.</p>
|
||||||
|
<p>For example, using the following model.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.db import models
|
||||||
|
from django.utils.timezone import now
|
||||||
|
|
||||||
|
class Account(models.Model):
|
||||||
|
owner = models.ForeignKey('auth.user')
|
||||||
|
name = models.CharField(max_length=100)
|
||||||
|
created = models.DateTimeField(auto_now_add=True)
|
||||||
|
payment_expiry = models.DateTimeField()
|
||||||
|
|
||||||
|
def has_expired(self):
|
||||||
|
return now() > self.payment_expiry
|
||||||
|
</code></pre>
|
||||||
|
<p>A serializer definition that looked like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import serializers
|
||||||
|
|
||||||
|
class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
expired = serializers.Field(source='has_expired')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
fields = ('url', 'owner', 'name', 'expired')
|
||||||
|
</code></pre>
|
||||||
|
<p>Would produce output similar to:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'url': 'http://example.com/api/accounts/3/',
|
||||||
|
'owner': 'http://example.com/api/users/12/',
|
||||||
|
'name': 'FooCorp business account',
|
||||||
|
'expired': True
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>By default, the <code>Field</code> class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.</p>
|
||||||
|
<p>You can customize this behavior by overriding the <code>.to_native(self, value)</code> method.</p>
|
||||||
|
<h2 id="writablefield">WritableField</h2>
|
||||||
|
<p>A field that supports both read and write operations. By itself <code>WritableField</code> does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the <code>.to_native(self, value)</code> and <code>.from_native(self, value)</code> methods.</p>
|
||||||
|
<h2 id="modelfield">ModelField</h2>
|
||||||
|
<p>A generic field that can be tied to any arbitrary model field. The <code>ModelField</code> class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.</p>
|
||||||
|
<p>The <code>ModelField</code> class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a <code>ModelField</code>, it must be passed a field that is attached to an instantiated model. For example: <code>ModelField(model_field=MyModel()._meta.get_field('custom_field'))</code></p>
|
||||||
|
<p><strong>Signature:</strong> <code>ModelField(model_field=<Django ModelField instance>)</code></p>
|
||||||
|
<h2 id="serializermethodfield">SerializerMethodField</h2>
|
||||||
|
<p>This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to <code>self</code>), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from django.utils.timezone import now
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
class UserSerializer(serializers.ModelSerializer):
|
||||||
|
days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
|
||||||
|
def get_days_since_joined(self, obj):
|
||||||
|
return (now() - obj.date_joined).days
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="typed-fields">Typed Fields</h1>
|
||||||
|
<p>These fields represent basic datatypes, and support both reading and writing values.</p>
|
||||||
|
<h2 id="booleanfield">BooleanField</h2>
|
||||||
|
<p>A Boolean representation.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.BooleanField</code>.</p>
|
||||||
|
<h2 id="charfield">CharField</h2>
|
||||||
|
<p>A text representation, optionally validates the text to be shorter than <code>max_length</code> and longer than <code>min_length</code>.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.CharField</code>
|
||||||
|
or <code>django.db.models.fields.TextField</code>.</p>
|
||||||
|
<p><strong>Signature:</strong> <code>CharField(max_length=None, min_length=None)</code></p>
|
||||||
|
<h2 id="urlfield">URLField</h2>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.URLField</code>. Uses Django's <code>django.core.validators.URLValidator</code> for validation.</p>
|
||||||
|
<p><strong>Signature:</strong> <code>CharField(max_length=200, min_length=None)</code></p>
|
||||||
|
<h2 id="slugfield">SlugField</h2>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.SlugField</code>.</p>
|
||||||
|
<p><strong>Signature:</strong> <code>CharField(max_length=50, min_length=None)</code></p>
|
||||||
|
<h2 id="choicefield">ChoiceField</h2>
|
||||||
|
<p>A field that can accept a value out of a limited set of choices.</p>
|
||||||
|
<h2 id="emailfield">EmailField</h2>
|
||||||
|
<p>A text representation, validates the text to be a valid e-mail address.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.EmailField</code></p>
|
||||||
|
<h2 id="regexfield">RegexField</h2>
|
||||||
|
<p>A text representation, that validates the given value matches against a certain regular expression.</p>
|
||||||
|
<p>Uses Django's <code>django.core.validators.RegexValidator</code> for validation.</p>
|
||||||
|
<p>Corresponds to <code>django.forms.fields.RegexField</code></p>
|
||||||
|
<p><strong>Signature:</strong> <code>RegexField(regex, max_length=None, min_length=None)</code></p>
|
||||||
|
<h2 id="datetimefield">DateTimeField</h2>
|
||||||
|
<p>A date and time representation.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.DateTimeField</code></p>
|
||||||
|
<p>When using <code>ModelSerializer</code> or <code>HyperlinkedModelSerializer</code>, note that any model fields with <code>auto_now=True</code> or <code>auto_now_add=True</code> will use serializer fields that are <code>read_only=True</code> by default.</p>
|
||||||
|
<p>If you want to override this behavior, you'll need to declare the <code>DateTimeField</code> explicitly on the serializer. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CommentSerializer(serializers.ModelSerializer):
|
||||||
|
created = serializers.DateTimeField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Comment
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that by default, datetime representations are determined by the renderer in use, although this can be explicitly overridden as detailed below.</p>
|
||||||
|
<p>In the case of JSON this means the default datetime representation uses the <a href="http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">ECMA 262 date time string specification</a>. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: <code>2013-01-29T12:34:56.123Z</code>.</p>
|
||||||
|
<p><strong>Signature:</strong> <code>DateTimeField(format=None, input_formats=None)</code></p>
|
||||||
|
<ul>
|
||||||
|
<li><code>format</code> - A string representing the output format. If not specified, this defaults to <code>None</code>, which indicates that Python <code>datetime</code> objects should be returned by <code>to_native</code>. In this case the datetime encoding will be determined by the renderer. </li>
|
||||||
|
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>DATETIME_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>DateTime format strings may either be <a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style datetimes should be used. (eg <code>'2013-01-29T12:34:56.000000Z'</code>)</p>
|
||||||
|
<h2 id="datefield">DateField</h2>
|
||||||
|
<p>A date representation.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.DateField</code></p>
|
||||||
|
<p><strong>Signature:</strong> <code>DateField(format=None, input_formats=None)</code></p>
|
||||||
|
<ul>
|
||||||
|
<li><code>format</code> - A string representing the output format. If not specified, this defaults to <code>None</code>, which indicates that Python <code>date</code> objects should be returned by <code>to_native</code>. In this case the date encoding will be determined by the renderer.</li>
|
||||||
|
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>DATE_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Date format strings may either be <a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style dates should be used. (eg <code>'2013-01-29'</code>)</p>
|
||||||
|
<h2 id="timefield">TimeField</h2>
|
||||||
|
<p>A time representation.</p>
|
||||||
|
<p>Optionally takes <code>format</code> as parameter to replace the matching pattern.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.TimeField</code></p>
|
||||||
|
<p><strong>Signature:</strong> <code>TimeField(format=None, input_formats=None)</code></p>
|
||||||
|
<ul>
|
||||||
|
<li><code>format</code> - A string representing the output format. If not specified, this defaults to <code>None</code>, which indicates that Python <code>time</code> objects should be returned by <code>to_native</code>. In this case the time encoding will be determined by the renderer.</li>
|
||||||
|
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>TIME_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Time format strings may either be <a href="http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <a href="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style times should be used. (eg <code>'12:34:56.000000'</code>)</p>
|
||||||
|
<h2 id="integerfield">IntegerField</h2>
|
||||||
|
<p>An integer representation.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.IntegerField</code>, <code>django.db.models.fields.SmallIntegerField</code>, <code>django.db.models.fields.PositiveIntegerField</code> and <code>django.db.models.fields.PositiveSmallIntegerField</code></p>
|
||||||
|
<h2 id="floatfield">FloatField</h2>
|
||||||
|
<p>A floating point representation.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.FloatField</code>.</p>
|
||||||
|
<h2 id="decimalfield">DecimalField</h2>
|
||||||
|
<p>A decimal representation.</p>
|
||||||
|
<p>Corresponds to <code>django.db.models.fields.DecimalField</code>.</p>
|
||||||
|
<h2 id="filefield">FileField</h2>
|
||||||
|
<p>A file representation. Performs Django's standard FileField validation.</p>
|
||||||
|
<p>Corresponds to <code>django.forms.fields.FileField</code>.</p>
|
||||||
|
<p><strong>Signature:</strong> <code>FileField(max_length=None, allow_empty_file=False)</code></p>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<p><code>max_length</code> designates the maximum length for the file name.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p><code>allow_empty_file</code> designates if empty files are allowed.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="imagefield">ImageField</h2>
|
||||||
|
<p>An image representation.</p>
|
||||||
|
<p>Corresponds to <code>django.forms.fields.ImageField</code>.</p>
|
||||||
|
<p>Requires the <code>PIL</code> package.</p>
|
||||||
|
<p>Signature and validation is the same as with <code>FileField</code>.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note:</strong> <code>FileFields</code> and <code>ImageFields</code> are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
|
||||||
|
Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS">FILE_UPLOAD_HANDLERS</a> are used for handling uploaded files.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-fields">Custom fields</h1>
|
||||||
|
<p>If you want to create a custom field, you'll probably want to override either one or both of the <code>.to_native()</code> and <code>.from_native()</code> methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects.</p>
|
||||||
|
<p>The <code>.to_native()</code> method is called to convert the initial datatype into a primitive, serializable datatype. The <code>from_native()</code> method is called to restore a primitive datatype into it's initial representation.</p>
|
||||||
|
<h2 id="examples">Examples</h2>
|
||||||
|
<p>Let's look at an example of serializing a class that represents an RGB color value:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class Color(object):
|
||||||
|
"""
|
||||||
|
A color represented in the RGB colorspace.
|
||||||
|
"""
|
||||||
|
def __init__(self, red, green, blue):
|
||||||
|
assert(red >= 0 and green >= 0 and blue >= 0)
|
||||||
|
assert(red < 256 and green < 256 and blue < 256)
|
||||||
|
self.red, self.green, self.blue = red, green, blue
|
||||||
|
|
||||||
|
class ColourField(serializers.WritableField):
|
||||||
|
"""
|
||||||
|
Color objects are serialized into "rgb(#, #, #)" notation.
|
||||||
|
"""
|
||||||
|
def to_native(self, obj):
|
||||||
|
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
|
||||||
|
|
||||||
|
def from_native(self, data):
|
||||||
|
data = data.strip('rgb(').rstrip(')')
|
||||||
|
red, green, blue = [int(col) for col in data.split(',')]
|
||||||
|
return Color(red, green, blue)
|
||||||
|
</code></pre>
|
||||||
|
<p>By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override <code>.field_to_native()</code> and/or <code>.field_from_native()</code>.</p>
|
||||||
|
<p>As an example, let's create a field that can be used represent the class name of the object being serialized:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class ClassNameField(serializers.Field):
|
||||||
|
def field_to_native(self, obj, field_name):
|
||||||
|
"""
|
||||||
|
Serialize the object's class name.
|
||||||
|
"""
|
||||||
|
return obj.__class__
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
533
api-guide/filtering.html
Normal file
|
@ -0,0 +1,533 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Filtering</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Filtering, Generic Filtering, API Guide, Custom generic filtering">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="filtering-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 " href="../api-guide/pagination.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/throttling.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#filtering">Filtering</a></li>
|
||||||
|
<li><a href="#filtering-against-the-current-user">Filtering against the current user</a></li>
|
||||||
|
<li><a href="#filtering-against-the-url">Filtering against the URL</a></li>
|
||||||
|
<li><a href="#filtering-against-query-parameters">Filtering against query parameters</a></li>
|
||||||
|
<li class="main"><a href="#generic-filtering">Generic Filtering</a></li>
|
||||||
|
<li><a href="#setting-filter-backends">Setting filter backends</a></li>
|
||||||
|
<li><a href="#filtering-and-object-lookups">Filtering and object lookups</a></li>
|
||||||
|
<li><a href="#overriding-the-initial-queryset">Overriding the initial queryset</a></li>
|
||||||
|
<li class="main"><a href="#api-guide">API Guide</a></li>
|
||||||
|
<li><a href="#djangofilterbackend">DjangoFilterBackend</a></li>
|
||||||
|
<li><a href="#searchfilter">SearchFilter</a></li>
|
||||||
|
<li><a href="#orderingfilter">OrderingFilter</a></li>
|
||||||
|
<li><a href="#djangoobjectpermissionsfilter">DjangoObjectPermissionsFilter</a></li>
|
||||||
|
<li class="main"><a href="#custom-generic-filtering">Custom generic filtering</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/filters.py"><span class="label label-info">filters.py</span></a></p>
|
||||||
|
<h1 id="filtering">Filtering</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.</p>
|
||||||
|
<p>— <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters">Django documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.</p>
|
||||||
|
<p>The simplest way to filter the queryset of any view that subclasses <code>GenericAPIView</code> is to override the <code>.get_queryset()</code> method.</p>
|
||||||
|
<p>Overriding this method allows you to customize the queryset returned by the view in a number of different ways.</p>
|
||||||
|
<h2 id="filtering-against-the-current-user">Filtering against the current user</h2>
|
||||||
|
<p>You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.</p>
|
||||||
|
<p>You can do so by filtering based on the value of <code>request.user</code>.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from myapp.models import Purchase
|
||||||
|
from myapp.serializers import PurchaseSerializer
|
||||||
|
from rest_framework import generics
|
||||||
|
|
||||||
|
class PurchaseList(generics.ListAPIView)
|
||||||
|
serializer_class = PurchaseSerializer
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
"""
|
||||||
|
This view should return a list of all the purchases
|
||||||
|
for the currently authenticated user.
|
||||||
|
"""
|
||||||
|
user = self.request.user
|
||||||
|
return Purchase.objects.filter(purchaser=user)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="filtering-against-the-url">Filtering against the URL</h2>
|
||||||
|
<p>Another style of filtering might involve restricting the queryset based on some part of the URL. </p>
|
||||||
|
<p>For example if your URL config contained an entry like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
|
||||||
|
</code></pre>
|
||||||
|
<p>You could then write a view that returned a purchase queryset filtered by the username portion of the URL:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class PurchaseList(generics.ListAPIView)
|
||||||
|
serializer_class = PurchaseSerializer
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
"""
|
||||||
|
This view should return a list of all the purchases for
|
||||||
|
the user as determined by the username portion of the URL.
|
||||||
|
"""
|
||||||
|
username = self.kwargs['username']
|
||||||
|
return Purchase.objects.filter(purchaser__username=username)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="filtering-against-query-parameters">Filtering against query parameters</h2>
|
||||||
|
<p>A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.</p>
|
||||||
|
<p>We can override <code>.get_queryset()</code> to deal with URLs such as <code>http://example.com/api/purchases?username=denvercoder9</code>, and filter the queryset only if the <code>username</code> parameter is included in the URL:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class PurchaseList(generics.ListAPIView)
|
||||||
|
serializer_class = PurchaseSerializer
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
"""
|
||||||
|
Optionally restricts the returned purchases to a given user,
|
||||||
|
by filtering against a `username` query parameter in the URL.
|
||||||
|
"""
|
||||||
|
queryset = Purchase.objects.all()
|
||||||
|
username = self.request.QUERY_PARAMS.get('username', None)
|
||||||
|
if username is not None:
|
||||||
|
queryset = queryset.filter(purchaser__username=username)
|
||||||
|
return queryset
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="generic-filtering">Generic Filtering</h1>
|
||||||
|
<p>As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.</p>
|
||||||
|
<h2 id="setting-filter-backends">Setting filter backends</h2>
|
||||||
|
<p>The default filter backends may be set globally, using the <code>DEFAULT_FILTER_BACKENDS</code> setting. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also set the filter backends on a per-view, or per-viewset basis,
|
||||||
|
using the <code>GenericAPIView</code> class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from myapp.serializers import UserSerializer
|
||||||
|
from rest_framework import filters
|
||||||
|
from rest_framework import generics
|
||||||
|
|
||||||
|
class UserListView(generics.ListAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer = UserSerializer
|
||||||
|
filter_backends = (filters.DjangoFilterBackend,)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="filtering-and-object-lookups">Filtering and object lookups</h2>
|
||||||
|
<p>Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.</p>
|
||||||
|
<p>For instance, given the previous example, and a product with an id of <code>4675</code>, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/products/4675/?category=clothing&max_price=10.00
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="overriding-the-initial-queryset">Overriding the initial queryset</h2>
|
||||||
|
<p>Note that you can use both an overridden <code>.get_queryset()</code> and generic filtering together, and everything will work as expected. For example, if <code>Product</code> had a many-to-many relationship with <code>User</code>, named <code>purchase</code>, you might want to write a view like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class PurchasedProductsList(generics.ListAPIView):
|
||||||
|
"""
|
||||||
|
Return a list of all the products that the authenticated
|
||||||
|
user has ever purchased, with optional filtering.
|
||||||
|
"""
|
||||||
|
model = Product
|
||||||
|
serializer_class = ProductSerializer
|
||||||
|
filter_class = ProductFilter
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
user = self.request.user
|
||||||
|
return user.purchase_set.all()
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-guide">API Guide</h1>
|
||||||
|
<h2 id="djangofilterbackend">DjangoFilterBackend</h2>
|
||||||
|
<p>The <code>DjangoFilterBackend</code> class supports highly customizable field filtering, using the <a href="https://github.com/alex/django-filter">django-filter package</a>. </p>
|
||||||
|
<p>To use REST framework's <code>DjangoFilterBackend</code>, first install <code>django-filter</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>pip install django-filter
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="specifying-filter-fields">Specifying filter fields</h4>
|
||||||
|
<p>If all you need is simple equality-based filtering, you can set a <code>filter_fields</code> attribute on the view, or viewset, listing the set of fields you wish to filter against.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class ProductList(generics.ListAPIView):
|
||||||
|
queryset = Product.objects.all()
|
||||||
|
serializer_class = ProductSerializer
|
||||||
|
filter_fields = ('category', 'in_stock')
|
||||||
|
</code></pre>
|
||||||
|
<p>This will automatically create a <code>FilterSet</code> class for the given fields, and will allow you to make requests such as:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/products?category=clothing&in_stock=True
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="specifying-a-filterset">Specifying a FilterSet</h4>
|
||||||
|
<p>For more advanced filtering requirements you can specify a <code>FilterSet</code> class that should be used by the view. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>import django_filters
|
||||||
|
from myapp.models import Product
|
||||||
|
from myapp.serializers import ProductSerializer
|
||||||
|
from rest_framework import generics
|
||||||
|
|
||||||
|
class ProductFilter(django_filters.FilterSet):
|
||||||
|
min_price = django_filters.NumberFilter(name="price", lookup_type='gte')
|
||||||
|
max_price = django_filters.NumberFilter(name="price", lookup_type='lte')
|
||||||
|
class Meta:
|
||||||
|
model = Product
|
||||||
|
fields = ['category', 'in_stock', 'min_price', 'max_price']
|
||||||
|
|
||||||
|
class ProductList(generics.ListAPIView):
|
||||||
|
queryset = Product.objects.all()
|
||||||
|
serializer_class = ProductSerializer
|
||||||
|
filter_class = ProductFilter
|
||||||
|
</code></pre>
|
||||||
|
<p>Which will allow you to make requests such as:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/products?category=clothing&max_price=10.00
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also span relationships using <code>django-filter</code>, let's assume that each
|
||||||
|
product has foreign key to <code>Manufacturer</code> model, so we create filter that
|
||||||
|
filters using <code>Manufacturer</code> name. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>import django_filters
|
||||||
|
from myapp.models import Product
|
||||||
|
from myapp.serializers import ProductSerializer
|
||||||
|
from rest_framework import generics
|
||||||
|
|
||||||
|
class ProductFilter(django_filters.FilterSet):
|
||||||
|
class Meta:
|
||||||
|
model = Product
|
||||||
|
fields = ['category', 'in_stock', 'manufacturer__name`]
|
||||||
|
</code></pre>
|
||||||
|
<p>This enables us to make queries like:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/products?manufacturer__name=foo
|
||||||
|
</code></pre>
|
||||||
|
<p>This is nice, but it shows underlying model structure in REST API, which may
|
||||||
|
be undesired, but you can use:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>import django_filters
|
||||||
|
from myapp.models import Product
|
||||||
|
from myapp.serializers import ProductSerializer
|
||||||
|
from rest_framework import generics
|
||||||
|
|
||||||
|
class ProductFilter(django_filters.FilterSet):
|
||||||
|
|
||||||
|
manufacturer = django_filters.CharFilter(name="manufacturer__name")
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Product
|
||||||
|
fields = ['category', 'in_stock', 'manufacturer`]
|
||||||
|
</code></pre>
|
||||||
|
<p>And now you can execute:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/products?manufacturer=foo
|
||||||
|
</code></pre>
|
||||||
|
<p>For more details on using filter sets see the <a href="https://django-filter.readthedocs.org/en/latest/index.html">django-filter documentation</a>.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Hints & Tips</strong></p>
|
||||||
|
<ul>
|
||||||
|
<li>By default filtering is not enabled. If you want to use <code>DjangoFilterBackend</code> remember to make sure it is installed by using the <code>'DEFAULT_FILTER_BACKENDS'</code> setting.</li>
|
||||||
|
<li>When using boolean fields, you should use the values <code>True</code> and <code>False</code> in the URL query parameters, rather than <code>0</code>, <code>1</code>, <code>true</code> or <code>false</code>. (The allowed boolean values are currently hardwired in Django's <a href="https://github.com/django/django/blob/master/django/forms/widgets.py">NullBooleanSelect implementation</a>.) </li>
|
||||||
|
<li><code>django-filter</code> supports filtering across relationships, using Django's double-underscore syntax.</li>
|
||||||
|
<li>For Django 1.3 support, make sure to install <code>django-filter</code> version 0.5.4, as later versions drop support for 1.3.</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h2 id="searchfilter">SearchFilter</h2>
|
||||||
|
<p>The <code>SearchFilter</code> class supports simple single query parameter based searching, and is based on the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django admin's search functionality</a>.</p>
|
||||||
|
<p>The <code>SearchFilter</code> class will only be applied if the view has a <code>search_fields</code> attribute set. The <code>search_fields</code> attribute should be a list of names of text type fields on the model, such as <code>CharField</code> or <code>TextField</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserListView(generics.ListAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer = UserSerializer
|
||||||
|
filter_backends = (filters.SearchFilter,)
|
||||||
|
search_fields = ('username', 'email')
|
||||||
|
</code></pre>
|
||||||
|
<p>This will allow the client to filter the items in the list by making queries such as:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/users?search=russell
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>search_fields = ('username', 'email', 'profile__profession')
|
||||||
|
</code></pre>
|
||||||
|
<p>By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.</p>
|
||||||
|
<p>The search behavior may be restricted by prepending various characters to the <code>search_fields</code>.</p>
|
||||||
|
<ul>
|
||||||
|
<li>'^' Starts-with search.</li>
|
||||||
|
<li>'=' Exact matches.</li>
|
||||||
|
<li>'@' Full-text search. (Currently only supported Django's MySQL backend.)</li>
|
||||||
|
</ul>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>search_fields = ('=username', '=email')
|
||||||
|
</code></pre>
|
||||||
|
<p>For more details, see the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django documentation</a>.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="orderingfilter">OrderingFilter</h2>
|
||||||
|
<p>The <code>OrderingFilter</code> class supports simple query parameter controlled ordering of results. To specify the result order, set a query parameter named <code>'ordering'</code> to the required field name. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/users?ordering=username
|
||||||
|
</code></pre>
|
||||||
|
<p>The client may also specify reverse orderings by prefixing the field name with '-', like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/users?ordering=-username
|
||||||
|
</code></pre>
|
||||||
|
<p>Multiple orderings may also be specified:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>http://example.com/api/users?ordering=account,username
|
||||||
|
</code></pre>
|
||||||
|
<p>If an <code>ordering</code> attribute is set on the view, this will be used as the default ordering.</p>
|
||||||
|
<p>Typically you'd instead control this by setting <code>order_by</code> on the initial queryset, but using the <code>ordering</code> parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserListView(generics.ListAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer = UserSerializer
|
||||||
|
filter_backends = (filters.OrderingFilter,)
|
||||||
|
ordering = ('username',)
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>ordering</code> attribute may be either a string or a list/tuple of strings.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="djangoobjectpermissionsfilter">DjangoObjectPermissionsFilter</h2>
|
||||||
|
<p>The <code>DjangoObjectPermissionsFilter</code> is intended to be used together with the <a href="http://pythonhosted.org/django-guardian/"><code>django-guardian</code></a> package, with custom <code>'view'</code> permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.</p>
|
||||||
|
<p>This filter class must be used with views that provide either a <code>queryset</code> or a <code>model</code> attribute.</p>
|
||||||
|
<p>If you're using <code>DjangoObjectPermissionsFilter</code>, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass <code>DjangoObjectPermissions</code> and add <code>'view'</code> permissions to the <code>perms_map</code> attribute.</p>
|
||||||
|
<p>A complete example using both <code>DjangoObjectPermissionsFilter</code> and <code>DjangoObjectPermissions</code> might look something like this.</p>
|
||||||
|
<p><strong>permissions.py</strong>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CustomObjectPermissions(permissions.DjangoObjectPermissions):
|
||||||
|
"""
|
||||||
|
Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
|
||||||
|
"""
|
||||||
|
perms_map = {
|
||||||
|
'GET': ['%(app_label)s.view_%(model_name)s'],
|
||||||
|
'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
|
||||||
|
'HEAD': ['%(app_label)s.view_%(model_name)s'],
|
||||||
|
'POST': ['%(app_label)s.add_%(model_name)s'],
|
||||||
|
'PUT': ['%(app_label)s.change_%(model_name)s'],
|
||||||
|
'PATCH': ['%(app_label)s.change_%(model_name)s'],
|
||||||
|
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p><strong>views.py</strong>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class EventViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
Viewset that only lists events if user has 'view' permissions, and only
|
||||||
|
allows operations on individual events if user has appropriate 'view', 'add',
|
||||||
|
'change' or 'delete' permissions.
|
||||||
|
"""
|
||||||
|
queryset = Event.objects.all()
|
||||||
|
serializer = EventSerializer
|
||||||
|
filter_backends = (filters.DjangoObjectPermissionsFilter,)
|
||||||
|
permission_classes = (myapp.permissions.CustomObjectPermissions,)
|
||||||
|
</code></pre>
|
||||||
|
<p>For more information on adding <code>'view'</code> permissions for models, see the <a href="http://pythonhosted.org/django-guardian/userguide/assign.html">relevant section</a> of the <code>django-guardian</code> documentation, and <a href="http://blog.nyaruka.com/adding-a-view-permission-to-django-models">this blogpost</a>.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-generic-filtering">Custom generic filtering</h1>
|
||||||
|
<p>You can also provide your own generic filtering backend, or write an installable app for other developers to use.</p>
|
||||||
|
<p>To do so override <code>BaseFilterBackend</code>, and override the <code>.filter_queryset(self, request, queryset, view)</code> method. The method should return a new, filtered queryset.</p>
|
||||||
|
<p>As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>For example, you might need to restrict users to only being able to see objects they created.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class IsOwnerFilterBackend(filters.BaseFilterBackend):
|
||||||
|
"""
|
||||||
|
Filter that only allows users to see their own objects.
|
||||||
|
"""
|
||||||
|
def filter_queryset(self, request, queryset, view):
|
||||||
|
return queryset.filter(owner=request.user)
|
||||||
|
</code></pre>
|
||||||
|
<p>We could achieve the same behavior by overriding <code>get_queryset()</code> on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
290
api-guide/format-suffixes.html
Normal file
|
@ -0,0 +1,290 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Format suffixes</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Format suffixes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="format-suffixes-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 " href="../api-guide/reverse.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/content-negotiation.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#format-suffixes">Format suffixes</a></li>
|
||||||
|
<li><a href="#format_suffix_patterns">format_suffix_patterns</a></li>
|
||||||
|
<li><a href="#accept-headers-vs-format-suffixes">Accept headers vs. format suffixes</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/urlpatterns.py"><span class="label label-info">urlpatterns.py</span></a></p>
|
||||||
|
<h1 id="format-suffixes">Format suffixes</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Section 6.2.1 does not say that content negotiation should be
|
||||||
|
used all the time.</p>
|
||||||
|
<p>— Roy Fielding, <a href="http://tech.groups.yahoo.com/group/rest-discuss/message/5857">REST discuss mailing list</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. </p>
|
||||||
|
<p>Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.</p>
|
||||||
|
<h2 id="format_suffix_patterns">format_suffix_patterns</h2>
|
||||||
|
<p><strong>Signature</strong>: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None)</p>
|
||||||
|
<p>Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided.</p>
|
||||||
|
<p>Arguments:</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>urlpatterns</strong>: Required. A URL pattern list.</li>
|
||||||
|
<li><strong>suffix_required</strong>: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to <code>False</code>, meaning that suffixes are optional by default.</li>
|
||||||
|
<li><strong>allowed</strong>: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. </li>
|
||||||
|
</ul>
|
||||||
|
<p>Example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.urlpatterns import format_suffix_patterns
|
||||||
|
|
||||||
|
urlpatterns = patterns('blog.views',
|
||||||
|
url(r'^/$', 'api_root'),
|
||||||
|
url(r'^comments/$', 'comment_list'),
|
||||||
|
url(r'^comments/(?P<pk>[0-9]+)/$', 'comment_detail')
|
||||||
|
)
|
||||||
|
|
||||||
|
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
|
||||||
|
</code></pre>
|
||||||
|
<p>When using <code>format_suffix_patterns</code>, you must make sure to add the <code>'format'</code> keyword argument to the corresponding views. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@api_view(('GET', 'POST'))
|
||||||
|
def comment_list(request, format=None):
|
||||||
|
# do stuff...
|
||||||
|
</code></pre>
|
||||||
|
<p>Or with class based views:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CommentList(APIView):
|
||||||
|
def get(self, request, format=None):
|
||||||
|
# do stuff...
|
||||||
|
|
||||||
|
def post(self, request, format=None):
|
||||||
|
# do stuff...
|
||||||
|
</code></pre>
|
||||||
|
<p>The name of the kwarg used may be modified by using the <code>FORMAT_SUFFIX_KWARG</code> setting.</p>
|
||||||
|
<p>Also note that <code>format_suffix_patterns</code> does not support descending into <code>include</code> URL patterns.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="accept-headers-vs-format-suffixes">Accept headers vs. format suffixes</h2>
|
||||||
|
<p>There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that <code>HTTP Accept</code> headers should always be used instead.</p>
|
||||||
|
<p>It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: </p>
|
||||||
|
<p>“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, <a href="http://tech.groups.yahoo.com/group/rest-discuss/message/14844">REST discuss mailing list</a></p>
|
||||||
|
<p>The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
506
api-guide/generic-views.html
Normal file
|
@ -0,0 +1,506 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Generic views</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Generic views, API Reference, Mixins, Concrete View Classes, Customizing the generic views">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="generic-views-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 " href="../api-guide/viewsets.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/views.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#generic-views">Generic views</a></li>
|
||||||
|
<li><a href="#examples">Examples</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#genericapiview">GenericAPIView</a></li>
|
||||||
|
<li class="main"><a href="#mixins">Mixins</a></li>
|
||||||
|
<li><a href="#listmodelmixin">ListModelMixin</a></li>
|
||||||
|
<li><a href="#createmodelmixin">CreateModelMixin</a></li>
|
||||||
|
<li><a href="#retrievemodelmixin">RetrieveModelMixin</a></li>
|
||||||
|
<li><a href="#updatemodelmixin">UpdateModelMixin</a></li>
|
||||||
|
<li><a href="#destroymodelmixin">DestroyModelMixin</a></li>
|
||||||
|
<li class="main"><a href="#concrete-view-classes">Concrete View Classes</a></li>
|
||||||
|
<li><a href="#createapiview">CreateAPIView</a></li>
|
||||||
|
<li><a href="#listapiview">ListAPIView</a></li>
|
||||||
|
<li><a href="#retrieveapiview">RetrieveAPIView</a></li>
|
||||||
|
<li><a href="#destroyapiview">DestroyAPIView</a></li>
|
||||||
|
<li><a href="#updateapiview">UpdateAPIView</a></li>
|
||||||
|
<li><a href="#listcreateapiview">ListCreateAPIView</a></li>
|
||||||
|
<li><a href="#retrieveupdateapiview">RetrieveUpdateAPIView</a></li>
|
||||||
|
<li><a href="#retrievedestroyapiview">RetrieveDestroyAPIView</a></li>
|
||||||
|
<li><a href="#retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</a></li>
|
||||||
|
<li class="main"><a href="#customizing-the-generic-views">Customizing the generic views</a></li>
|
||||||
|
<li><a href="#creating-custom-mixins">Creating custom mixins</a></li>
|
||||||
|
<li><a href="#creating-custom-base-classes">Creating custom base classes</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/mixins.py"><span class="label label-info">mixins.py</span></a>
|
||||||
|
<a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/generics.py"><span class="label label-info">generics.py</span></a></p>
|
||||||
|
<h1 id="generic-views">Generic views</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.</p>
|
||||||
|
<p>— <a href="https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views">Django Documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.</p>
|
||||||
|
<p>The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.</p>
|
||||||
|
<p>If the generic views don't suit the needs of your API, you can drop down to using the regular <code>APIView</code> class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.</p>
|
||||||
|
<h2 id="examples">Examples</h2>
|
||||||
|
<p>Typically when using the generic views, you'll override the view, and set several class attributes.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from myapp.serializers import UserSerializer
|
||||||
|
from rest_framework import generics
|
||||||
|
from rest_framework.permissions import IsAdminUser
|
||||||
|
|
||||||
|
class UserList(generics.ListCreateAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
permission_classes = (IsAdminUser,)
|
||||||
|
paginate_by = 100
|
||||||
|
</code></pre>
|
||||||
|
<p>For more complex cases you might also want to override various methods on the view class. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserList(generics.ListCreateAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
permission_classes = (IsAdminUser,)
|
||||||
|
|
||||||
|
def get_paginate_by(self):
|
||||||
|
"""
|
||||||
|
Use smaller pagination for HTML representations.
|
||||||
|
"""
|
||||||
|
if self.request.accepted_renderer.format == 'html':
|
||||||
|
return 20
|
||||||
|
return 100
|
||||||
|
</code></pre>
|
||||||
|
<p>For very simple cases you might want to pass through any class attributes using the <code>.as_view()</code> method. For example, your URLconf might include something the following entry.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="genericapiview">GenericAPIView</h2>
|
||||||
|
<p>This class extends REST framework's <code>APIView</code> class, adding commonly required behavior for standard list and detail views.</p>
|
||||||
|
<p>Each of the concrete generic views provided is built by combining <code>GenericAPIView</code>, with one or more mixin classes.</p>
|
||||||
|
<h3 id="attributes">Attributes</h3>
|
||||||
|
<p><strong>Basic settings</strong>:</p>
|
||||||
|
<p>The following attributes control the basic view behavior.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>queryset</code> - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the <code>get_queryset()</code> method.</li>
|
||||||
|
<li><code>serializer_class</code> - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the <code>get_serializer_class()</code> method.</li>
|
||||||
|
<li><code>lookup_field</code> - The model field that should be used to for performing object lookup of individual model instances. Defaults to <code>'pk'</code>. Note that when using hyperlinked APIs you'll need to ensure that <em>both</em> the API views <em>and</em> the serializer classes set the lookup fields if you need to use a custom value.</li>
|
||||||
|
<li><code>lookup_url_kwarg</code> - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as <code>lookup_field</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Shortcuts</strong>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>model</code> - This shortcut may be used instead of setting either (or both) of the <code>queryset</code>/<code>serializer_class</code> attributes, although using the explicit style is generally preferred. If used instead of <code>serializer_class</code>, then then <code>DEFAULT_MODEL_SERIALIZER_CLASS</code> setting will determine the base serializer class. Note that <code>model</code> is only ever used for generating a default queryset or serializer class - the <code>queryset</code> and <code>serializer_class</code> attributes are always preferred if provided.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Pagination</strong>:</p>
|
||||||
|
<p>The following attributes are used to control pagination when used with list views.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>paginate_by</code> - The size of pages to use with paginated data. If set to <code>None</code> then pagination is turned off. If unset this uses the same value as the <code>PAGINATE_BY</code> setting, which defaults to <code>None</code>.</li>
|
||||||
|
<li><code>paginate_by_param</code> - The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If unset this uses the same value as the <code>PAGINATE_BY_PARAM</code> setting, which defaults to <code>None</code>.</li>
|
||||||
|
<li><code>pagination_serializer_class</code> - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the <code>DEFAULT_PAGINATION_SERIALIZER_CLASS</code> setting.</li>
|
||||||
|
<li><code>page_kwarg</code> - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to <code>'page'</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Filtering</strong>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>filter_backends</code> - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the <code>DEFAULT_FILTER_BACKENDS</code> setting.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="methods">Methods</h3>
|
||||||
|
<p><strong>Base methods</strong>:</p>
|
||||||
|
<h4 id="get_querysetself"><code>get_queryset(self)</code></h4>
|
||||||
|
<p>Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the <code>queryset</code> attribute, or the default queryset for the model if the <code>model</code> shortcut is being used.</p>
|
||||||
|
<p>May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def get_queryset(self):
|
||||||
|
user = self.request.user
|
||||||
|
return user.accounts.all()
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="get_objectself"><code>get_object(self)</code></h4>
|
||||||
|
<p>Returns an object instance that should be used for detail views. Defaults to using the <code>lookup_field</code> parameter to filter the base queryset.</p>
|
||||||
|
<p>May be overridden to provide more complex behavior such as object lookups based on more than one URL kwarg.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def get_object(self):
|
||||||
|
queryset = self.get_queryset()
|
||||||
|
filter = {}
|
||||||
|
for field in self.multiple_lookup_fields:
|
||||||
|
filter[field] = self.kwargs[field]
|
||||||
|
|
||||||
|
obj = get_object_or_404(queryset, **filter)
|
||||||
|
self.check_object_permissions(self.request, obj)
|
||||||
|
return obj
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that if your API doesn't include any object level permissions, you may optionally exclude the <code>`self.check_object_permissions, and simply return the object from the</code>get_object_or_404` lookup.</p>
|
||||||
|
<h4 id="get_filter_backendsself"><code>get_filter_backends(self)</code></h4>
|
||||||
|
<p>Returns the classes that should be used to filter the queryset. Defaults to returning the <code>filter_backends</code> attribute.</p>
|
||||||
|
<p>May be override to provide more complex behavior with filters, as using different (or even exlusive) lists of filter_backends depending on different criteria.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def get_filter_backends(self):
|
||||||
|
if "geo_route" in self.request.QUERY_PARAMS:
|
||||||
|
return (GeoRouteFilter, CategoryFilter)
|
||||||
|
elif "geo_point" in self.request.QUERY_PARAMS:
|
||||||
|
return (GeoPointFilter, CategoryFilter)
|
||||||
|
|
||||||
|
return (CategoryFilter,)
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="get_serializer_classself"><code>get_serializer_class(self)</code></h4>
|
||||||
|
<p>Returns the class that should be used for the serializer. Defaults to returning the <code>serializer_class</code> attribute, or dynamically generating a serializer class if the <code>model</code> shortcut is being used.</p>
|
||||||
|
<p>May be override to provide dynamic behavior such as using different serializers for read and write operations, or providing different serializers to different types of users.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def get_serializer_class(self):
|
||||||
|
if self.request.user.is_staff:
|
||||||
|
return FullAccountSerializer
|
||||||
|
return BasicAccountSerializer
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="get_paginate_byself"><code>get_paginate_by(self)</code></h4>
|
||||||
|
<p>Returns the page size to use with pagination. By default this uses the <code>paginate_by</code> attribute, and may be overridden by the client if the <code>paginate_by_param</code> attribute is set.</p>
|
||||||
|
<p>You may want to override this method to provide more complex behavior such as modifying page sizes based on the media type of the response.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def get_paginate_by(self):
|
||||||
|
if self.request.accepted_renderer.format == 'html':
|
||||||
|
return 20
|
||||||
|
return 100
|
||||||
|
</code></pre>
|
||||||
|
<p><strong>Save hooks</strong>:</p>
|
||||||
|
<p>The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by <code>GenericAPIView</code>, but they are overridden and used by some of the mixin classes.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>pre_save(self, obj)</code> - A hook that is called before saving an object.</li>
|
||||||
|
<li><code>post_save(self, obj, created=False)</code> - A hook that is called after saving an object.</li>
|
||||||
|
</ul>
|
||||||
|
<p>The <code>pre_save</code> method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def pre_save(self, obj):
|
||||||
|
"""
|
||||||
|
Set the object's owner, based on the incoming request.
|
||||||
|
"""
|
||||||
|
obj.owner = self.request.user
|
||||||
|
</code></pre>
|
||||||
|
<p>Remember that the <code>pre_save()</code> method is not called by <code>GenericAPIView</code> itself, but it is called by <code>create()</code> and <code>update()</code> methods on the <code>CreateModelMixin</code> and <code>UpdateModelMixin</code> classes.</p>
|
||||||
|
<p><strong>Other methods</strong>:</p>
|
||||||
|
<p>You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using <code>GenericAPIView</code>.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>get_serializer_context(self)</code> - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including <code>'request'</code>, <code>'view'</code> and <code>'format'</code> keys.</li>
|
||||||
|
<li><code>get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)</code> - Returns a serializer instance.</li>
|
||||||
|
<li><code>get_pagination_serializer(self, page)</code> - Returns a serializer instance to use with paginated data.</li>
|
||||||
|
<li><code>paginate_queryset(self, queryset)</code> - Paginate a queryset if required, either returning a page object, or <code>None</code> if pagination is not configured for this view.</li>
|
||||||
|
<li><code>filter_queryset(self, queryset)</code> - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h1 id="mixins">Mixins</h1>
|
||||||
|
<p>The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods such as <code>.get()</code> and <code>.post()</code> directly. This allows for more flexible composition of behavior.</p>
|
||||||
|
<h2 id="listmodelmixin">ListModelMixin</h2>
|
||||||
|
<p>Provides a <code>.list(request, *args, **kwargs)</code> method, that implements listing a queryset.</p>
|
||||||
|
<p>If the queryset is populated, this returns a <code>200 OK</code> response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.</p>
|
||||||
|
<p>If the queryset is empty this returns a <code>200 OK</code> response, unless the <code>.allow_empty</code> attribute on the view is set to <code>False</code>, in which case it will return a <code>404 Not Found</code>.</p>
|
||||||
|
<h2 id="createmodelmixin">CreateModelMixin</h2>
|
||||||
|
<p>Provides a <code>.create(request, *args, **kwargs)</code> method, that implements creating and saving a new model instance.</p>
|
||||||
|
<p>If an object is created this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response. If the representation contains a key named <code>url</code>, then the <code>Location</code> header of the response will be populated with that value.</p>
|
||||||
|
<p>If the request data provided for creating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
|
||||||
|
<h2 id="retrievemodelmixin">RetrieveModelMixin</h2>
|
||||||
|
<p>Provides a <code>.retrieve(request, *args, **kwargs)</code> method, that implements returning an existing model instance in a response.</p>
|
||||||
|
<p>If an object can be retrieved this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response. Otherwise it will return a <code>404 Not Found</code>.</p>
|
||||||
|
<h2 id="updatemodelmixin">UpdateModelMixin</h2>
|
||||||
|
<p>Provides a <code>.update(request, *args, **kwargs)</code> method, that implements updating and saving an existing model instance.</p>
|
||||||
|
<p>Also provides a <code>.partial_update(request, *args, **kwargs)</code> method, which is similar to the <code>update</code> method, except that all fields for the update will be optional. This allows support for HTTP <code>PATCH</code> requests.</p>
|
||||||
|
<p>If an object is updated this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response.</p>
|
||||||
|
<p>If an object is created, for example when making a <code>DELETE</code> request followed by a <code>PUT</code> request to the same URL, this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response.</p>
|
||||||
|
<p>If the request data provided for updating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
|
||||||
|
<h2 id="destroymodelmixin">DestroyModelMixin</h2>
|
||||||
|
<p>Provides a <code>.destroy(request, *args, **kwargs)</code> method, that implements deletion of an existing model instance.</p>
|
||||||
|
<p>If an object is deleted this returns a <code>204 No Content</code> response, otherwise it will return a <code>404 Not Found</code>.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="concrete-view-classes">Concrete View Classes</h1>
|
||||||
|
<p>The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.</p>
|
||||||
|
<h2 id="createapiview">CreateAPIView</h2>
|
||||||
|
<p>Used for <strong>create-only</strong> endpoints.</p>
|
||||||
|
<p>Provides a <code>post</code> method handler.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
|
||||||
|
<h2 id="listapiview">ListAPIView</h2>
|
||||||
|
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
|
||||||
|
<p>Provides a <code>get</code> method handler.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a></p>
|
||||||
|
<h2 id="retrieveapiview">RetrieveAPIView</h2>
|
||||||
|
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||||||
|
<p>Provides a <code>get</code> method handler.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a></p>
|
||||||
|
<h2 id="destroyapiview">DestroyAPIView</h2>
|
||||||
|
<p>Used for <strong>delete-only</strong> endpoints for a <strong>single model instance</strong>.</p>
|
||||||
|
<p>Provides a <code>delete</code> method handler.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
|
||||||
|
<h2 id="updateapiview">UpdateAPIView</h2>
|
||||||
|
<p>Used for <strong>update-only</strong> endpoints for a <strong>single model instance</strong>.</p>
|
||||||
|
<p>Provides <code>put</code> and <code>patch</code> method handlers.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
|
||||||
|
<h2 id="listcreateapiview">ListCreateAPIView</h2>
|
||||||
|
<p>Used for <strong>read-write</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
|
||||||
|
<p>Provides <code>get</code> and <code>post</code> method handlers.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
|
||||||
|
<h2 id="retrieveupdateapiview">RetrieveUpdateAPIView</h2>
|
||||||
|
<p>Used for <strong>read or update</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||||||
|
<p>Provides <code>get</code>, <code>put</code> and <code>patch</code> method handlers.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
|
||||||
|
<h2 id="retrievedestroyapiview">RetrieveDestroyAPIView</h2>
|
||||||
|
<p>Used for <strong>read or delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||||||
|
<p>Provides <code>get</code> and <code>delete</code> method handlers.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
|
||||||
|
<h2 id="retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</h2>
|
||||||
|
<p>Used for <strong>read-write-delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||||||
|
<p>Provides <code>get</code>, <code>put</code>, <code>patch</code> and <code>delete</code> method handlers.</p>
|
||||||
|
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="customizing-the-generic-views">Customizing the generic views</h1>
|
||||||
|
<p>Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.</p>
|
||||||
|
<h2 id="creating-custom-mixins">Creating custom mixins</h2>
|
||||||
|
<p>For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class MultipleFieldLookupMixin(object):
|
||||||
|
"""
|
||||||
|
Apply this mixin to any view or viewset to get multiple field filtering
|
||||||
|
based on a `lookup_fields` attribute, instead of the default single field filtering.
|
||||||
|
"""
|
||||||
|
def get_object(self):
|
||||||
|
queryset = self.get_queryset() # Get the base queryset
|
||||||
|
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||||||
|
filter = {}
|
||||||
|
for field in self.lookup_fields:
|
||||||
|
filter[field] = self.kwargs[field]
|
||||||
|
return get_object_or_404(queryset, **filter) # Lookup the object
|
||||||
|
</code></pre>
|
||||||
|
<p>You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
lookup_fields = ('account', 'username')
|
||||||
|
</code></pre>
|
||||||
|
<p>Using custom mixins is a good option if you have custom behavior that needs to be used</p>
|
||||||
|
<h2 id="creating-custom-base-classes">Creating custom base classes</h2>
|
||||||
|
<p>If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class BaseRetrieveView(MultipleFieldLookupMixin,
|
||||||
|
generics.RetrieveAPIView):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
|
||||||
|
generics.RetrieveUpdateDestroyAPIView):
|
||||||
|
pass
|
||||||
|
</code></pre>
|
||||||
|
<p>Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
366
api-guide/pagination.html
Normal file
|
@ -0,0 +1,366 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Pagination</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Pagination, Custom pagination serializers">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="pagination-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 " href="../api-guide/content-negotiation.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/filtering.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#pagination">Pagination</a></li>
|
||||||
|
<li><a href="#paginating-basic-data">Paginating basic data</a></li>
|
||||||
|
<li><a href="#paginating-querysets">Paginating QuerySets</a></li>
|
||||||
|
<li><a href="#pagination-in-the-generic-views">Pagination in the generic views</a></li>
|
||||||
|
<li class="main"><a href="#custom-pagination-serializers">Custom pagination serializers</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li><a href="#using-your-custom-pagination-serializer">Using your custom pagination serializer</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/pagination.py"><span class="label label-info">pagination.py</span></a></p>
|
||||||
|
<h1 id="pagination">Pagination</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.</p>
|
||||||
|
<p>— <a href="https://docs.djangoproject.com/en/dev/topics/pagination/">Django documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>REST framework includes a <code>PaginationSerializer</code> class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. </p>
|
||||||
|
<h2 id="paginating-basic-data">Paginating basic data</h2>
|
||||||
|
<p>Let's start by taking a look at an example from the Django documentation.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.core.paginator import Paginator
|
||||||
|
|
||||||
|
objects = ['john', 'paul', 'george', 'ringo']
|
||||||
|
paginator = Paginator(objects, 2)
|
||||||
|
page = paginator.page(1)
|
||||||
|
page.object_list
|
||||||
|
# ['john', 'paul']
|
||||||
|
</code></pre>
|
||||||
|
<p>At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.pagination import PaginationSerializer
|
||||||
|
|
||||||
|
serializer = PaginationSerializer(instance=page)
|
||||||
|
serializer.data
|
||||||
|
# {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']}
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>context</code> argument of the <code>PaginationSerializer</code> class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>request = RequestFactory().get('/foobar')
|
||||||
|
serializer = PaginationSerializer(instance=page, context={'request': request})
|
||||||
|
serializer.data
|
||||||
|
# {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
|
||||||
|
</code></pre>
|
||||||
|
<p>We could now return that data in a <code>Response</code> object, and it would be rendered into the correct media type.</p>
|
||||||
|
<h2 id="paginating-querysets">Paginating QuerySets</h2>
|
||||||
|
<p>Our first example worked because we were using primitive objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself.</p>
|
||||||
|
<p>We can do this using the <code>object_serializer_class</code> attribute on the inner <code>Meta</code> class of the pagination serializer. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserSerializer(serializers.ModelSerializer):
|
||||||
|
"""
|
||||||
|
Serializes user querysets.
|
||||||
|
"""
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ('username', 'email')
|
||||||
|
|
||||||
|
class PaginatedUserSerializer(pagination.PaginationSerializer):
|
||||||
|
"""
|
||||||
|
Serializes page objects of user querysets.
|
||||||
|
"""
|
||||||
|
class Meta:
|
||||||
|
object_serializer_class = UserSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>We could now use our pagination serializer in a view like this.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@api_view('GET')
|
||||||
|
def user_list(request):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
paginator = Paginator(queryset, 20)
|
||||||
|
|
||||||
|
page = request.QUERY_PARAMS.get('page')
|
||||||
|
try:
|
||||||
|
users = paginator.page(page)
|
||||||
|
except PageNotAnInteger:
|
||||||
|
# If page is not an integer, deliver first page.
|
||||||
|
users = paginator.page(1)
|
||||||
|
except EmptyPage:
|
||||||
|
# If page is out of range (e.g. 9999),
|
||||||
|
# deliver last page of results.
|
||||||
|
users = paginator.page(paginator.num_pages)
|
||||||
|
|
||||||
|
serializer_context = {'request': request}
|
||||||
|
serializer = PaginatedUserSerializer(users,
|
||||||
|
context=serializer_context)
|
||||||
|
return Response(serializer.data)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="pagination-in-the-generic-views">Pagination in the generic views</h2>
|
||||||
|
<p>The generic class based views <code>ListAPIView</code> and <code>ListCreateAPIView</code> provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.</p>
|
||||||
|
<p>The default pagination style may be set globally, using the <code>DEFAULT_PAGINATION_SERIALIZER_CLASS</code>, <code>PAGINATE_BY</code>, <code>PAGINATE_BY_PARAM</code>, and <code>MAX_PAGINATE_BY</code> settings. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'PAGINATE_BY': 10, # Default to 10
|
||||||
|
'PAGINATE_BY_PARAM': 'page_size', # Allow client to override, using `?page_size=xxx`.
|
||||||
|
'MAX_PAGINATE_BY': 100 # Maximum limit allowed when using `?page_size=xxx`.
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also set the pagination style on a per-view basis, using the <code>ListAPIView</code> generic class-based view.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class PaginatedListView(ListAPIView):
|
||||||
|
queryset = ExampleModel.objects.all()
|
||||||
|
serializer_class = ExampleModelSerializer
|
||||||
|
paginate_by = 10
|
||||||
|
paginate_by_param = 'page_size'
|
||||||
|
max_paginate_by = 100
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that using a <code>paginate_by</code> value of <code>None</code> will turn off pagination for the view.</p>
|
||||||
|
<p>For more complex requirements such as serialization that differs depending on the requested media type you can override the <code>.get_paginate_by()</code> and <code>.get_pagination_serializer_class()</code> methods.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-pagination-serializers">Custom pagination serializers</h1>
|
||||||
|
<p>To create a custom pagination serializer class you should override <code>pagination.BasePaginationSerializer</code> and set the fields that you want the serializer to return.</p>
|
||||||
|
<p>You can also override the name used for the object list field, by setting the <code>results_field</code> attribute, which defaults to <code>'results'</code>.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import pagination
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
class LinksSerializer(serializers.Serializer):
|
||||||
|
next = pagination.NextPageField(source='*')
|
||||||
|
prev = pagination.PreviousPageField(source='*')
|
||||||
|
|
||||||
|
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
|
||||||
|
links = LinksSerializer(source='*') # Takes the page object as the source
|
||||||
|
total_results = serializers.Field(source='paginator.count')
|
||||||
|
|
||||||
|
results_field = 'objects'
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="using-your-custom-pagination-serializer">Using your custom pagination serializer</h2>
|
||||||
|
<p>To have your custom pagination serializer be used by default, use the <code>DEFAULT_PAGINATION_SERIALIZER_CLASS</code> setting:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_PAGINATION_SERIALIZER_CLASS':
|
||||||
|
'example_app.pagination.CustomPaginationSerializer',
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Alternatively, to set your custom pagination serializer on a per-view basis, use the <code>pagination_serializer_class</code> attribute on a generic class based view:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class PaginatedListView(generics.ListAPIView):
|
||||||
|
model = ExampleModel
|
||||||
|
pagination_serializer_class = CustomPaginationSerializer
|
||||||
|
paginate_by = 10
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
376
api-guide/parsers.html
Normal file
|
@ -0,0 +1,376 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Parsers</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Parsers, API Reference, Custom parsers, Third party packages">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="parsers-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 " href="../api-guide/renderers.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/routers.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#parsers">Parsers</a></li>
|
||||||
|
<li><a href="#how-the-parser-is-determined">How the parser is determined</a></li>
|
||||||
|
<li><a href="#setting-the-parsers">Setting the parsers</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#jsonparser">JSONParser</a></li>
|
||||||
|
<li><a href="#yamlparser">YAMLParser</a></li>
|
||||||
|
<li><a href="#xmlparser">XMLParser</a></li>
|
||||||
|
<li><a href="#formparser">FormParser</a></li>
|
||||||
|
<li><a href="#multipartparser">MultiPartParser</a></li>
|
||||||
|
<li><a href="#fileuploadparser">FileUploadParser</a></li>
|
||||||
|
<li class="main"><a href="#custom-parsers">Custom parsers</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li class="main"><a href="#third-party-packages">Third party packages</a></li>
|
||||||
|
<li><a href="#messagepack">MessagePack</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/parsers.py"><span class="label label-info">parsers.py</span></a></p>
|
||||||
|
<h1 id="parsers">Parsers</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Machine interacting web services tend to use more
|
||||||
|
structured formats for sending data than form-encoded, since they're
|
||||||
|
sending more complex data than simple forms</p>
|
||||||
|
<p>— Malcom Tredinnick, <a href="https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion">Django developers group</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.</p>
|
||||||
|
<h2 id="how-the-parser-is-determined">How the parser is determined</h2>
|
||||||
|
<p>The set of valid parsers for a view is always defined as a list of classes. When either <code>request.DATA</code> or <code>request.FILES</code> is accessed, REST framework will examine the <code>Content-Type</code> header on the incoming request, and determine which parser to use to parse the request content.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note</strong>: When developing client applications always remember to make sure you're setting the <code>Content-Type</code> header when sending data in an HTTP request.</p>
|
||||||
|
<p>If you don't set the content type, most clients will default to using <code>'application/x-www-form-urlencoded'</code>, which may not be what you wanted.</p>
|
||||||
|
<p>As an example, if you are sending <code>json</code> encoded data using jQuery with the <a href="http://api.jquery.com/jQuery.ajax/">.ajax() method</a>, you should make sure to include the <code>contentType: 'application/json'</code> setting.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="setting-the-parsers">Setting the parsers</h2>
|
||||||
|
<p>The default set of parsers may be set globally, using the <code>DEFAULT_PARSER_CLASSES</code> setting. For example, the following settings would allow requests with <code>YAML</code> content.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_PARSER_CLASSES': (
|
||||||
|
'rest_framework.parsers.YAMLParser',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also set the parsers used for an individual view, or viewset,
|
||||||
|
using the <code>APIView</code> class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.parsers import YAMLParser
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
class ExampleView(APIView):
|
||||||
|
"""
|
||||||
|
A view that can accept POST requests with YAML content.
|
||||||
|
"""
|
||||||
|
parser_classes = (YAMLParser,)
|
||||||
|
|
||||||
|
def post(self, request, format=None):
|
||||||
|
return Response({'received data': request.DATA})
|
||||||
|
</code></pre>
|
||||||
|
<p>Or, if you're using the <code>@api_view</code> decorator with function based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@api_view(['POST'])
|
||||||
|
@parser_classes((YAMLParser,))
|
||||||
|
def example_view(request, format=None):
|
||||||
|
"""
|
||||||
|
A view that can accept POST requests with YAML content.
|
||||||
|
"""
|
||||||
|
return Response({'received data': request.DATA})
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="jsonparser">JSONParser</h2>
|
||||||
|
<p>Parses <code>JSON</code> request content.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>application/json</code></p>
|
||||||
|
<h2 id="yamlparser">YAMLParser</h2>
|
||||||
|
<p>Parses <code>YAML</code> request content.</p>
|
||||||
|
<p>Requires the <code>pyyaml</code> package to be installed.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>application/yaml</code></p>
|
||||||
|
<h2 id="xmlparser">XMLParser</h2>
|
||||||
|
<p>Parses REST framework's default style of <code>XML</code> request content.</p>
|
||||||
|
<p>Note that the <code>XML</code> markup language is typically used as the base language for more strictly defined domain-specific languages, such as <code>RSS</code>, <code>Atom</code>, and <code>XHTML</code>.</p>
|
||||||
|
<p>If you are considering using <code>XML</code> for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.</p>
|
||||||
|
<p>Requires the <code>defusedxml</code> package to be installed.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>application/xml</code></p>
|
||||||
|
<h2 id="formparser">FormParser</h2>
|
||||||
|
<p>Parses HTML form content. <code>request.DATA</code> will be populated with a <code>QueryDict</code> of data, <code>request.FILES</code> will be populated with an empty <code>QueryDict</code> of data.</p>
|
||||||
|
<p>You will typically want to use both <code>FormParser</code> and <code>MultiPartParser</code> together in order to fully support HTML form data.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>application/x-www-form-urlencoded</code></p>
|
||||||
|
<h2 id="multipartparser">MultiPartParser</h2>
|
||||||
|
<p>Parses multipart HTML form content, which supports file uploads. Both <code>request.DATA</code> and <code>request.FILES</code> will be populated with a <code>QueryDict</code>.</p>
|
||||||
|
<p>You will typically want to use both <code>FormParser</code> and <code>MultiPartParser</code> together in order to fully support HTML form data.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>multipart/form-data</code></p>
|
||||||
|
<h2 id="fileuploadparser">FileUploadParser</h2>
|
||||||
|
<p>Parses raw file upload content. The <code>request.DATA</code> property will be an empty <code>QueryDict</code>, and <code>request.FILES</code> will be a dictionary with a single key <code>'file'</code> containing the uploaded file.</p>
|
||||||
|
<p>If the view used with <code>FileUploadParser</code> is called with a <code>filename</code> URL keyword argument, then that argument will be used as the filename. If it is called without a <code>filename</code> URL keyword argument, then the client must set the filename in the <code>Content-Disposition</code> HTTP header. For example <code>Content-Disposition: attachment; filename=upload.jpg</code>.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>*/*</code></p>
|
||||||
|
<h5 id="notes">Notes:</h5>
|
||||||
|
<ul>
|
||||||
|
<li>The <code>FileUploadParser</code> is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the <code>MultiPartParser</code> parser instead.</li>
|
||||||
|
<li>Since this parser's <code>media_type</code> matches any content type, <code>FileUploadParser</code> should generally be the only parser set on an API view.</li>
|
||||||
|
<li><code>FileUploadParser</code> respects Django's standard <code>FILE_UPLOAD_HANDLERS</code> setting, and the <code>request.upload_handlers</code> attribute. See the <a href="https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers">Django documentation</a> for more details.</li>
|
||||||
|
</ul>
|
||||||
|
<h5 id="basic-usage-example">Basic usage example:</h5>
|
||||||
|
<pre class="prettyprint lang-py"><code>class FileUploadView(views.APIView):
|
||||||
|
parser_classes = (FileUploadParser,)
|
||||||
|
|
||||||
|
def put(self, request, filename, format=None):
|
||||||
|
file_obj = request.FILES['file']
|
||||||
|
# ...
|
||||||
|
# do some staff with uploaded file
|
||||||
|
# ...
|
||||||
|
return Response(status=204)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-parsers">Custom parsers</h1>
|
||||||
|
<p>To implement a custom parser, you should override <code>BaseParser</code>, set the <code>.media_type</code> property, and implement the <code>.parse(self, stream, media_type, parser_context)</code> method.</p>
|
||||||
|
<p>The method should return the data that will be used to populate the <code>request.DATA</code> property.</p>
|
||||||
|
<p>The arguments passed to <code>.parse()</code> are:</p>
|
||||||
|
<h3 id="stream">stream</h3>
|
||||||
|
<p>A stream-like object representing the body of the request.</p>
|
||||||
|
<h3 id="media_type">media_type</h3>
|
||||||
|
<p>Optional. If provided, this is the media type of the incoming request content.</p>
|
||||||
|
<p>Depending on the request's <code>Content-Type:</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>"text/plain; charset=utf-8"</code>.</p>
|
||||||
|
<h3 id="parser_context">parser_context</h3>
|
||||||
|
<p>Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.</p>
|
||||||
|
<p>By default this will include the following keys: <code>view</code>, <code>request</code>, <code>args</code>, <code>kwargs</code>.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>The following is an example plaintext parser that will populate the <code>request.DATA</code> property with a string representing the body of the request. </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class PlainTextParser(BaseParser):
|
||||||
|
"""
|
||||||
|
Plain text parser.
|
||||||
|
"""
|
||||||
|
|
||||||
|
media_type = 'text/plain'
|
||||||
|
|
||||||
|
def parse(self, stream, media_type=None, parser_context=None):
|
||||||
|
"""
|
||||||
|
Simply return a string representing the body of the request.
|
||||||
|
"""
|
||||||
|
return stream.read()
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="third-party-packages">Third party packages</h1>
|
||||||
|
<p>The following third party packages are also available.</p>
|
||||||
|
<h2 id="messagepack">MessagePack</h2>
|
||||||
|
<p><a href="https://github.com/juanriaza/django-rest-framework-msgpack">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>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
419
api-guide/permissions.html
Normal file
|
@ -0,0 +1,419 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Permissions</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Permissions, API Reference, Custom permissions, Third party packages">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="permissions-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 " href="../api-guide/throttling.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/authentication.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#permissions">Permissions</a></li>
|
||||||
|
<li><a href="#how-permissions-are-determined">How permissions are determined</a></li>
|
||||||
|
<li><a href="#object-level-permissions">Object level permissions</a></li>
|
||||||
|
<li><a href="#setting-the-permission-policy">Setting the permission policy</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#allowany">AllowAny</a></li>
|
||||||
|
<li><a href="#isauthenticated">IsAuthenticated</a></li>
|
||||||
|
<li><a href="#isadminuser">IsAdminUser</a></li>
|
||||||
|
<li><a href="#isauthenticatedorreadonly">IsAuthenticatedOrReadOnly</a></li>
|
||||||
|
<li><a href="#djangomodelpermissions">DjangoModelPermissions</a></li>
|
||||||
|
<li><a href="#djangomodelpermissionsoranonreadonly">DjangoModelPermissionsOrAnonReadOnly</a></li>
|
||||||
|
<li><a href="#tokenhasreadwritescope">TokenHasReadWriteScope</a></li>
|
||||||
|
<li class="main"><a href="#custom-permissions">Custom permissions</a></li>
|
||||||
|
<li><a href="#examples">Examples</a></li>
|
||||||
|
<li class="main"><a href="#third-party-packages">Third party packages</a></li>
|
||||||
|
<li><a href="#drf-any-permissions">DRF Any Permissions</a></li>
|
||||||
|
<li><a href="#composed-permissions">Composed Permissions</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/permissions.py"><span class="label label-info">permissions.py</span></a></p>
|
||||||
|
<h1 id="permissions">Permissions</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.</p>
|
||||||
|
<p>— <a href="https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html">Apple Developer Documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Together with <a href="authentication.html">authentication</a> and <a href="throttling.html">throttling</a>, permissions determine whether a request should be granted or denied access.</p>
|
||||||
|
<p>Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the <code>request.user</code> and <code>request.auth</code> properties to determine if the incoming request should be permitted.</p>
|
||||||
|
<h2 id="how-permissions-are-determined">How permissions are determined</h2>
|
||||||
|
<p>Permissions in REST framework are always defined as a list of permission classes. </p>
|
||||||
|
<p>Before running the main body of the view each permission in the list is checked.
|
||||||
|
If any permission check fails an <code>exceptions.PermissionDenied</code> exception will be raised, and the main body of the view will not run.</p>
|
||||||
|
<h2 id="object-level-permissions">Object level permissions</h2>
|
||||||
|
<p>REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.</p>
|
||||||
|
<p>Object level permissions are run by REST framework's generic views when <code>.get_object()</code> is called.
|
||||||
|
As with view level permissions, an <code>exceptions.PermissionDenied</code> exception will be raised if the user is not allowed to act on the given object.</p>
|
||||||
|
<p>If you're writing your own views and want to enforce object level permissions,
|
||||||
|
or if you override the <code>get_object</code> method on a generic view, then you'll need to explicitly call the <code>.check_object_permissions(request, obj)</code> method on the view at the point at which you've retrieved the object.</p>
|
||||||
|
<p>This will either raise a <code>PermissionDenied</code> or <code>NotAuthenticated</code> exception, or simply return if the view has the appropriate permissions.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def get_object(self):
|
||||||
|
obj = get_object_or_404(self.get_queryset())
|
||||||
|
self.check_object_permissions(self.request, obj)
|
||||||
|
return obj
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="setting-the-permission-policy">Setting the permission policy</h2>
|
||||||
|
<p>The default permission policy may be set globally, using the <code>DEFAULT_PERMISSION_CLASSES</code> setting. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_PERMISSION_CLASSES': (
|
||||||
|
'rest_framework.permissions.IsAuthenticated',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>If not specified, this setting defaults to allowing unrestricted access:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>'DEFAULT_PERMISSION_CLASSES': (
|
||||||
|
'rest_framework.permissions.AllowAny',
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also set the authentication policy on a per-view, or per-viewset basis,
|
||||||
|
using the <code>APIView</code> class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.permissions import IsAuthenticated
|
||||||
|
from rest_framework.responses import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
class ExampleView(APIView):
|
||||||
|
permission_classes = (IsAuthenticated,)
|
||||||
|
|
||||||
|
def get(self, request, format=None):
|
||||||
|
content = {
|
||||||
|
'status': 'request was permitted'
|
||||||
|
}
|
||||||
|
return Response(content)
|
||||||
|
</code></pre>
|
||||||
|
<p>Or, if you're using the <code>@api_view</code> decorator with function based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@api_view('GET')
|
||||||
|
@permission_classes((IsAuthenticated, ))
|
||||||
|
def example_view(request, format=None):
|
||||||
|
content = {
|
||||||
|
'status': 'request was permitted'
|
||||||
|
}
|
||||||
|
return Response(content)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="allowany">AllowAny</h2>
|
||||||
|
<p>The <code>AllowAny</code> permission class will allow unrestricted access, <strong>regardless of if the request was authenticated or unauthenticated</strong>.</p>
|
||||||
|
<p>This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.</p>
|
||||||
|
<h2 id="isauthenticated">IsAuthenticated</h2>
|
||||||
|
<p>The <code>IsAuthenticated</code> permission class will deny permission to any unauthenticated user, and allow permission otherwise.</p>
|
||||||
|
<p>This permission is suitable if you want your API to only be accessible to registered users.</p>
|
||||||
|
<h2 id="isadminuser">IsAdminUser</h2>
|
||||||
|
<p>The <code>IsAdminUser</code> permission class will deny permission to any user, unless <code>user.is_staff</code> is <code>True</code> in which case permission will be allowed.</p>
|
||||||
|
<p>This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.</p>
|
||||||
|
<h2 id="isauthenticatedorreadonly">IsAuthenticatedOrReadOnly</h2>
|
||||||
|
<p>The <code>IsAuthenticatedOrReadOnly</code> will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; <code>GET</code>, <code>HEAD</code> or <code>OPTIONS</code>.</p>
|
||||||
|
<p>This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.</p>
|
||||||
|
<h2 id="djangomodelpermissions">DjangoModelPermissions</h2>
|
||||||
|
<p>This permission class ties into Django's standard <code>django.contrib.auth</code> <a href="https://docs.djangoproject.com/en/1.0/topics/auth/#permissions">model permissions</a>. When applied to a view that has a <code>.model</code> property, authorization will only be granted if the user <em>is authenticated</em> and has the <em>relevant model permissions</em> assigned.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>POST</code> requests require the user to have the <code>add</code> permission on the model.</li>
|
||||||
|
<li><code>PUT</code> and <code>PATCH</code> requests require the user to have the <code>change</code> permission on the model.</li>
|
||||||
|
<li><code>DELETE</code> requests require the user to have the <code>delete</code> permission on the model.</li>
|
||||||
|
</ul>
|
||||||
|
<p>The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a <code>view</code> model permission for <code>GET</code> requests.</p>
|
||||||
|
<p>To use custom model permissions, override <code>DjangoModelPermissions</code> and set the <code>.perms_map</code> property. Refer to the source code for details.</p>
|
||||||
|
<h2 id="djangomodelpermissionsoranonreadonly">DjangoModelPermissionsOrAnonReadOnly</h2>
|
||||||
|
<p>Similar to <code>DjangoModelPermissions</code>, but also allows unauthenticated users to have read-only access to the API.</p>
|
||||||
|
<h2 id="djangoobjectpermissions">DjangoObjectPermissions</h2>
|
||||||
|
<p>This permission class ties into Django's standard <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions">object permissions framework</a> that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as <a href="https://github.com/lukaszb/django-guardian">django-guardian</a>.</p>
|
||||||
|
<p>When applied to a view that has a <code>.model</code> property, authorization will only be granted if the user <em>is authenticated</em> and has the <em>relevant per-object permissions</em> and <em>relevant model permissions</em> assigned.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>POST</code> requests require the user to have the <code>add</code> permission on the model instance.</li>
|
||||||
|
<li><code>PUT</code> and <code>PATCH</code> requests require the user to have the <code>change</code> permission on the model instance.</li>
|
||||||
|
<li><code>DELETE</code> requests require the user to have the <code>delete</code> permission on the model instance.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Note that <code>DjangoObjectPermissions</code> <strong>does not</strong> require the <code>django-guardian</code> package, and should support other object-level backends equally well.</p>
|
||||||
|
<p>As with <code>DjangoModelPermissions</code> you can use custom model permissions by overriding <code>DjangoModelPermissions</code> and setting the <code>.perms_map</code> property. Refer to the source code for details. Note that if you add a custom <code>view</code> permission for <code>GET</code>, <code>HEAD</code> and <code>OPTIONS</code> requests, you'll probably also want to consider adding the <code>DjangoObjectPermissionsFilter</code> class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.</p>
|
||||||
|
<h2 id="tokenhasreadwritescope">TokenHasReadWriteScope</h2>
|
||||||
|
<p>This permission class is intended for use with either of the <code>OAuthAuthentication</code> and <code>OAuth2Authentication</code> classes, and ties into the scoping that their backends provide.</p>
|
||||||
|
<p>Requests with a safe methods of <code>GET</code>, <code>OPTIONS</code> or <code>HEAD</code> will be allowed if the authenticated token has read permission.</p>
|
||||||
|
<p>Requests for <code>POST</code>, <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> will be allowed if the authenticated token has write permission.</p>
|
||||||
|
<p>This permission class relies on the implementations of the <a href="http://code.larlet.fr/django-oauth-plus">django-oauth-plus</a> and <a href="https://github.com/caffeinehit/django-oauth2-provider">django-oauth2-provider</a> libraries, which both provide limited support for controlling the scope of access tokens:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>django-oauth-plus</code>: Tokens are associated with a <code>Resource</code> class which has a <code>name</code>, <code>url</code> and <code>is_readonly</code> properties.</li>
|
||||||
|
<li><code>django-oauth2-provider</code>: Tokens are associated with a bitwise <code>scope</code> attribute, that defaults to providing bitwise values for <code>read</code> and/or <code>write</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>If you require more advanced scoping for your API, such as restricting tokens to accessing a subset of functionality of your API then you will need to provide a custom permission class. See the source of the <code>django-oauth-plus</code> or <code>django-oauth2-provider</code> package for more details on scoping token access.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-permissions">Custom permissions</h1>
|
||||||
|
<p>To implement a custom permission, override <code>BasePermission</code> and implement either, or both, of the following methods:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>.has_permission(self, request, view)</code></li>
|
||||||
|
<li><code>.has_object_permission(self, request, view, obj)</code></li>
|
||||||
|
</ul>
|
||||||
|
<p>The methods should return <code>True</code> if the request should be granted access, and <code>False</code> otherwise.</p>
|
||||||
|
<p>If you need to test if a request is a read operation or a write operation, you should check the request method against the constant <code>SAFE_METHODS</code>, which is a tuple containing <code>'GET'</code>, <code>'OPTIONS'</code> and <code>'HEAD'</code>. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>if request.method in permissions.SAFE_METHODS:
|
||||||
|
# Check permissions for read-only request
|
||||||
|
else:
|
||||||
|
# Check permissions for write request
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note</strong>: In versions 2.0 and 2.1, the signature for the permission checks always included an optional <code>obj</code> parameter, like so: <code>.has_permission(self, request, view, obj=None)</code>. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.</p>
|
||||||
|
<p>As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a <code>PendingDeprecationWarning</code>, which is silent by default. In 2.3 this will be escalated to a <code>DeprecationWarning</code>, and in 2.4 the old-style signature will be removed.</p>
|
||||||
|
<p>For more details see the <a href="../topics/2.2-announcement.html">2.2 release announcement</a>.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="examples">Examples</h2>
|
||||||
|
<p>The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import permissions
|
||||||
|
|
||||||
|
class BlacklistPermission(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Global permission check for blacklisted IPs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def has_permission(self, request, view):
|
||||||
|
ip_addr = request.META['REMOTE_ADDR']
|
||||||
|
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
|
||||||
|
return not blacklisted
|
||||||
|
</code></pre>
|
||||||
|
<p>As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class IsOwnerOrReadOnly(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Object-level permission to only allow owners of an object to edit it.
|
||||||
|
Assumes the model instance has an `owner` attribute.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def has_object_permission(self, request, view, obj):
|
||||||
|
# Read permissions are allowed to any request,
|
||||||
|
# so we'll always allow GET, HEAD or OPTIONS requests.
|
||||||
|
if request.method in permissions.SAFE_METHODS:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Instance must have an attribute named `owner`.
|
||||||
|
return obj.owner == request.user
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling <code>self.check_object_permissions(request, obj)</code> from the view once you have the object instance. This call will raise an appropriate <code>APIException</code> if any object-level permission checks fail, and will otherwise simply return.</p>
|
||||||
|
<p>Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the <a href="filtering.html">filtering documentation</a> for more details.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="third-party-packages">Third party packages</h1>
|
||||||
|
<p>The following third party packages are also available.</p>
|
||||||
|
<h2 id="drf-any-permissions">DRF Any Permissions</h2>
|
||||||
|
<p>The <a href="https://github.com/kevin-brown/drf-any-permissions">DRF Any Permissions</a> packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view.</p>
|
||||||
|
<h2 id="composed-permissions">Composed Permissions</h2>
|
||||||
|
<p>The <a href="https://github.com/niwibe/djangorestframework-composed-permissions">Composed Permissions</a> package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
616
api-guide/relations.html
Normal file
|
@ -0,0 +1,616 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Serializer relations</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Serializer relations, API Reference, Nested relationships, Custom relational fields, Further notes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="relations-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 " href="../api-guide/authentication.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/fields.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#serializer-relations">Serializer relations</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#relatedfield">RelatedField</a></li>
|
||||||
|
<li><a href="#primarykeyrelatedfield">PrimaryKeyRelatedField</a></li>
|
||||||
|
<li><a href="#hyperlinkedrelatedfield">HyperlinkedRelatedField</a></li>
|
||||||
|
<li><a href="#slugrelatedfield">SlugRelatedField</a></li>
|
||||||
|
<li><a href="#hyperlinkedidentityfield">HyperlinkedIdentityField</a></li>
|
||||||
|
<li class="main"><a href="#nested-relationships">Nested relationships</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li class="main"><a href="#custom-relational-fields">Custom relational fields</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li class="main"><a href="#further-notes">Further notes</a></li>
|
||||||
|
<li><a href="#reverse-relations">Reverse relations</a></li>
|
||||||
|
<li><a href="#generic-relationships">Generic relationships</a></li>
|
||||||
|
<li><a href="#manytomanyfields-with-a-through-model">ManyToManyFields with a Through Model</a></li>
|
||||||
|
<li><a href="#advanced-hyperlinked-fields">Advanced Hyperlinked fields</a></li>
|
||||||
|
<li><a href="#deprecated-apis">Deprecated APIs</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/relations.py"><span class="label label-info">relations.py</span></a></p>
|
||||||
|
<h1 id="serializer-relations">Serializer relations</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Bad programmers worry about the code.
|
||||||
|
Good programmers worry about data structures and their relationships.</p>
|
||||||
|
<p>— <a href="http://lwn.net/Articles/193245/">Linus Torvalds</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Relational fields are used to represent model relationships. They can be applied to <code>ForeignKey</code>, <code>ManyToManyField</code> and <code>OneToOneField</code> relationships, as well as to reverse relationships, and custom relationships such as <code>GenericForeignKey</code>.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note:</strong> The relational fields are declared in <code>relations.py</code>, but by convention you should import them from the <code>serializers</code> module, using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.<FieldName></code>.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<p>In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class Album(models.Model):
|
||||||
|
album_name = models.CharField(max_length=100)
|
||||||
|
artist = models.CharField(max_length=100)
|
||||||
|
|
||||||
|
class Track(models.Model):
|
||||||
|
album = models.ForeignKey(Album, related_name='tracks')
|
||||||
|
order = models.IntegerField()
|
||||||
|
title = models.CharField(max_length=100)
|
||||||
|
duration = models.IntegerField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
unique_together = ('album', 'order')
|
||||||
|
order_by = 'order'
|
||||||
|
|
||||||
|
def __unicode__(self):
|
||||||
|
return '%d: %s' % (self.order, self.title)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="relatedfield">RelatedField</h2>
|
||||||
|
<p><code>RelatedField</code> may be used to represent the target of the relationship using its <code>__unicode__</code> method.</p>
|
||||||
|
<p>For example, the following serializer.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
tracks = RelatedField(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'tracks')
|
||||||
|
</code></pre>
|
||||||
|
<p>Would serialize to the following representation.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'album_name': 'Things We Lost In The Fire',
|
||||||
|
'artist': 'Low',
|
||||||
|
'tracks': [
|
||||||
|
'1: Sunflower',
|
||||||
|
'2: Whitetail',
|
||||||
|
'3: Dinosaur Act',
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>This field is read only.</p>
|
||||||
|
<p><strong>Arguments</strong>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="primarykeyrelatedfield">PrimaryKeyRelatedField</h2>
|
||||||
|
<p><code>PrimaryKeyRelatedField</code> may be used to represent the target of the relationship using its primary key.</p>
|
||||||
|
<p>For example, the following serializer:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'tracks')
|
||||||
|
</code></pre>
|
||||||
|
<p>Would serialize to a representation like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'album_name': 'The Roots',
|
||||||
|
'artist': 'Undun',
|
||||||
|
'tracks': [
|
||||||
|
89,
|
||||||
|
90,
|
||||||
|
91,
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>By default this field is read-write, although you can change this behavior using the <code>read_only</code> flag.</p>
|
||||||
|
<p><strong>Arguments</strong>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
|
||||||
|
<li><code>required</code> - If set to <code>False</code>, the field will accept values of <code>None</code> or the empty-string for nullable relationships.</li>
|
||||||
|
<li><code>queryset</code> - By default <code>ModelSerializer</code> classes will use the default queryset for the relationship. <code>Serializer</code> classes must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="hyperlinkedrelatedfield">HyperlinkedRelatedField</h2>
|
||||||
|
<p><code>HyperlinkedRelatedField</code> may be used to represent the target of the relationship using a hyperlink.</p>
|
||||||
|
<p>For example, the following serializer:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True,
|
||||||
|
view_name='track-detail')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'tracks')
|
||||||
|
</code></pre>
|
||||||
|
<p>Would serialize to a representation like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'album_name': 'Graceland',
|
||||||
|
'artist': 'Paul Simon',
|
||||||
|
'tracks': [
|
||||||
|
'http://www.example.com/api/tracks/45/',
|
||||||
|
'http://www.example.com/api/tracks/46/',
|
||||||
|
'http://www.example.com/api/tracks/47/',
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>By default this field is read-write, although you can change this behavior using the <code>read_only</code> flag.</p>
|
||||||
|
<p><strong>Arguments</strong>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>view_name</code> - The view name that should be used as the target of the relationship. <strong>required</strong>.</li>
|
||||||
|
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
|
||||||
|
<li><code>required</code> - If set to <code>False</code>, the field will accept values of <code>None</code> or the empty-string for nullable relationships.</li>
|
||||||
|
<li><code>queryset</code> - By default <code>ModelSerializer</code> classes will use the default queryset for the relationship. <code>Serializer</code> classes must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
|
||||||
|
<li><code>lookup_field</code> - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is <code>'pk'</code>.</li>
|
||||||
|
<li><code>format</code> - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the <code>format</code> argument.</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="slugrelatedfield">SlugRelatedField</h2>
|
||||||
|
<p><code>SlugRelatedField</code> may be used to represent the target of the relationship using a field on the target.</p>
|
||||||
|
<p>For example, the following serializer:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
tracks = serializers.SlugRelatedField(many=True, read_only=True,
|
||||||
|
slug_field='title')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'tracks')
|
||||||
|
</code></pre>
|
||||||
|
<p>Would serialize to a representation like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'album_name': 'Dear John',
|
||||||
|
'artist': 'Loney Dear',
|
||||||
|
'tracks': [
|
||||||
|
'Airport Surroundings',
|
||||||
|
'Everything Turns to You',
|
||||||
|
'I Was Only Going Out',
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>By default this field is read-write, although you can change this behavior using the <code>read_only</code> flag.</p>
|
||||||
|
<p>When using <code>SlugRelatedField</code> as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with <code>unique=True</code>.</p>
|
||||||
|
<p><strong>Arguments</strong>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>slug_field</code> - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, <code>username</code>. <strong>required</strong></li>
|
||||||
|
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
|
||||||
|
<li><code>required</code> - If set to <code>False</code>, the field will accept values of <code>None</code> or the empty-string for nullable relationships.</li>
|
||||||
|
<li><code>queryset</code> - By default <code>ModelSerializer</code> classes will use the default queryset for the relationship. <code>Serializer</code> classes must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="hyperlinkedidentityfield">HyperlinkedIdentityField</h2>
|
||||||
|
<p>This field can be applied as an identity relationship, such as the <code>'url'</code> field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'track_listing')
|
||||||
|
</code></pre>
|
||||||
|
<p>Would serialize to a representation like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'album_name': 'The Eraser',
|
||||||
|
'artist': 'Thom Yorke',
|
||||||
|
'track_listing': 'http://www.example.com/api/track_list/12/',
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>This field is always read-only.</p>
|
||||||
|
<p><strong>Arguments</strong>:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>view_name</code> - The view name that should be used as the target of the relationship. <strong>required</strong>.</li>
|
||||||
|
<li><code>lookup_field</code> - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is <code>'pk'</code>.</li>
|
||||||
|
<li><code>format</code> - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the <code>format</code> argument.</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h1 id="nested-relationships">Nested relationships</h1>
|
||||||
|
<p>Nested relationships can be expressed by using serializers as fields.</p>
|
||||||
|
<p>If the field is used to represent a to-many relationship, you should add the <code>many=True</code> flag to the serializer field.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>For example, the following serializer:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class TrackSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Track
|
||||||
|
fields = ('order', 'title')
|
||||||
|
|
||||||
|
class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
tracks = TrackSerializer(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'tracks')
|
||||||
|
</code></pre>
|
||||||
|
<p>Would serialize to a nested representation like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'album_name': 'The Grey Album',
|
||||||
|
'artist': 'Danger Mouse',
|
||||||
|
'tracks': [
|
||||||
|
{'order': 1, 'title': 'Public Service Announcement'},
|
||||||
|
{'order': 2, 'title': 'What More Can I Say'},
|
||||||
|
{'order': 3, 'title': 'Encore'},
|
||||||
|
...
|
||||||
|
],
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<h1 id="custom-relational-fields">Custom relational fields</h1>
|
||||||
|
<p>To implement a custom relational field, you should override <code>RelatedField</code>, and implement the <code>.to_native(self, value)</code> method. This method takes the target of the field as the <code>value</code> argument, and should return the representation that should be used to serialize the target.</p>
|
||||||
|
<p>If you want to implement a read-write relational field, you must also implement the <code>.from_native(self, data)</code> method, and add <code>read_only = False</code> to the class definition.</p>
|
||||||
|
<h2 id="example_1">Example</h2>
|
||||||
|
<p>For, example, we could define a relational field, to serialize a track to a custom string representation, using its ordering, title, and duration.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>import time
|
||||||
|
|
||||||
|
class TrackListingField(serializers.RelatedField):
|
||||||
|
def to_native(self, value):
|
||||||
|
duration = time.strftime('%M:%S', time.gmtime(value.duration))
|
||||||
|
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
|
||||||
|
|
||||||
|
class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
tracks = TrackListingField(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'tracks')
|
||||||
|
</code></pre>
|
||||||
|
<p>This custom field would then serialize to the following representation.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'album_name': 'Sometimes I Wish We Were an Eagle',
|
||||||
|
'artist': 'Bill Callahan',
|
||||||
|
'tracks': [
|
||||||
|
'Track 1: Jim Cain (04:39)',
|
||||||
|
'Track 2: Eid Ma Clack Shaw (04:19)',
|
||||||
|
'Track 3: The Wind and the Dove (04:34)',
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="further-notes">Further notes</h1>
|
||||||
|
<h2 id="reverse-relations">Reverse relations</h2>
|
||||||
|
<p>Note that reverse relationships are not automatically included by the <code>ModelSerializer</code> and <code>HyperlinkedModelSerializer</code> classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
fields = ('tracks', ...)
|
||||||
|
</code></pre>
|
||||||
|
<p>You'll normally want to ensure that you've set an appropriate <code>related_name</code> argument on the relationship, that you can use as the field name. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class Track(models.Model):
|
||||||
|
album = models.ForeignKey(Album, related_name='tracks')
|
||||||
|
...
|
||||||
|
</code></pre>
|
||||||
|
<p>If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the <code>fields</code> argument. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
fields = ('track_set', ...)
|
||||||
|
</code></pre>
|
||||||
|
<p>See the Django documentation on <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward">reverse relationships</a> for more details.</p>
|
||||||
|
<h2 id="generic-relationships">Generic relationships</h2>
|
||||||
|
<p>If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.</p>
|
||||||
|
<p>For example, given the following model for a tag, which has a generic relationship with other arbitrary models:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class TaggedItem(models.Model):
|
||||||
|
"""
|
||||||
|
Tags arbitrary model instances using a generic relation.
|
||||||
|
|
||||||
|
See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
|
||||||
|
"""
|
||||||
|
tag_name = models.SlugField()
|
||||||
|
content_type = models.ForeignKey(ContentType)
|
||||||
|
object_id = models.PositiveIntegerField()
|
||||||
|
tagged_object = GenericForeignKey('content_type', 'object_id')
|
||||||
|
|
||||||
|
def __unicode__(self):
|
||||||
|
return self.tag
|
||||||
|
</code></pre>
|
||||||
|
<p>And the following two models, which may be have associated tags:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class Bookmark(models.Model):
|
||||||
|
"""
|
||||||
|
A bookmark consists of a URL, and 0 or more descriptive tags.
|
||||||
|
"""
|
||||||
|
url = models.URLField()
|
||||||
|
tags = GenericRelation(TaggedItem)
|
||||||
|
|
||||||
|
|
||||||
|
class Note(models.Model):
|
||||||
|
"""
|
||||||
|
A note consists of some text, and 0 or more descriptive tags.
|
||||||
|
"""
|
||||||
|
text = models.CharField(max_length=1000)
|
||||||
|
tags = GenericRelation(TaggedItem)
|
||||||
|
</code></pre>
|
||||||
|
<p>We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class TaggedObjectRelatedField(serializers.RelatedField):
|
||||||
|
"""
|
||||||
|
A custom field to use for the `tagged_object` generic relationship.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def to_native(self, value):
|
||||||
|
"""
|
||||||
|
Serialize tagged objects to a simple textual representation.
|
||||||
|
"""
|
||||||
|
if isinstance(value, Bookmark):
|
||||||
|
return 'Bookmark: ' + value.url
|
||||||
|
elif isinstance(value, Note):
|
||||||
|
return 'Note: ' + value.text
|
||||||
|
raise Exception('Unexpected type of tagged object')
|
||||||
|
</code></pre>
|
||||||
|
<p>If you need the target of the relationship to have a nested representation, you can use the required serializers inside the <code>.to_native()</code> method:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code> def to_native(self, value):
|
||||||
|
"""
|
||||||
|
Serialize bookmark instances using a bookmark serializer,
|
||||||
|
and note instances using a note serializer.
|
||||||
|
"""
|
||||||
|
if isinstance(value, Bookmark):
|
||||||
|
serializer = BookmarkSerializer(value)
|
||||||
|
elif isinstance(value, Note):
|
||||||
|
serializer = NoteSerializer(value)
|
||||||
|
else:
|
||||||
|
raise Exception('Unexpected type of tagged object')
|
||||||
|
|
||||||
|
return serializer.data
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that reverse generic keys, expressed using the <code>GenericRelation</code> field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.</p>
|
||||||
|
<p>For more information see <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1">the Django documentation on generic relations</a>.</p>
|
||||||
|
<h2 id="manytomanyfields-with-a-through-model">ManyToManyFields with a Through Model</h2>
|
||||||
|
<p>By default, relational fields that target a <code>ManyToManyField</code> with a
|
||||||
|
<code>through</code> model specified are set to read-only.</p>
|
||||||
|
<p>If you explicitly specify a relational field pointing to a
|
||||||
|
<code>ManyToManyField</code> with a through model, be sure to set <code>read_only</code>
|
||||||
|
to <code>True</code>.</p>
|
||||||
|
<h2 id="advanced-hyperlinked-fields">Advanced Hyperlinked fields</h2>
|
||||||
|
<p>If you have very specific requirements for the style of your hyperlinked relationships you can override <code>HyperlinkedRelatedField</code>. </p>
|
||||||
|
<p>There are two methods you'll need to override.</p>
|
||||||
|
<h4 id="get_urlself-obj-view_name-request-format">get_url(self, obj, view_name, request, format)</h4>
|
||||||
|
<p>This method should return the URL that corresponds to the given object.</p>
|
||||||
|
<p>May raise a <code>NoReverseMatch</code> if the <code>view_name</code> and <code>lookup_field</code>
|
||||||
|
attributes are not configured to correctly match the URL conf.</p>
|
||||||
|
<h4 id="get_objectself-queryset-view_name-view_args-view_kwargs">get_object(self, queryset, view_name, view_args, view_kwargs)</h4>
|
||||||
|
<p>This method should the object that corresponds to the matched URL conf arguments.</p>
|
||||||
|
<p>May raise an <code>ObjectDoesNotExist</code> exception.</p>
|
||||||
|
<h3 id="example_2">Example</h3>
|
||||||
|
<p>For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this: </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
|
||||||
|
def get_url(self, obj, view_name, request, format):
|
||||||
|
kwargs = {'account': obj.account, 'slug': obj.slug}
|
||||||
|
return reverse(view_name, kwargs=kwargs, request=request, format=format)
|
||||||
|
|
||||||
|
def get_object(self, queryset, view_name, view_args, view_kwargs):
|
||||||
|
account = view_kwargs['account']
|
||||||
|
slug = view_kwargs['slug']
|
||||||
|
return queryset.get(account=account, slug=slug)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h2 id="deprecated-apis">Deprecated APIs</h2>
|
||||||
|
<p>The following classes have been deprecated, in favor of the <code>many=<bool></code> syntax.
|
||||||
|
They continue to function, but their usage will raise a <code>PendingDeprecationWarning</code>, which is silent by default.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>ManyRelatedField</code></li>
|
||||||
|
<li><code>ManyPrimaryKeyRelatedField</code></li>
|
||||||
|
<li><code>ManyHyperlinkedRelatedField</code></li>
|
||||||
|
<li><code>ManySlugRelatedField</code></li>
|
||||||
|
</ul>
|
||||||
|
<p>The <code>null=<bool></code> flag has been deprecated in favor of the <code>required=<bool></code> flag. It will continue to function, but will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<p>In the 2.3 release, these warnings will be escalated to a <code>DeprecationWarning</code>, which is loud by default.
|
||||||
|
In the 2.4 release, these parts of the API will be removed entirely.</p>
|
||||||
|
<p>For more details see the <a href="../topics/2.2-announcement.html">2.2 release announcement</a>.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
543
api-guide/renderers.html
Normal file
|
@ -0,0 +1,543 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Renderers</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Renderers, API Reference, Custom renderers, Advanced renderer usage, Third party packages">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="renderers-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 " href="../api-guide/serializers.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/parsers.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<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="#unicodejsonrenderer">UnicodeJSONRenderer</a></li>
|
||||||
|
<li><a href="#jsonprenderer">JSONPRenderer</a></li>
|
||||||
|
<li><a href="#yamlrenderer">YAMLRenderer</a></li>
|
||||||
|
<li><a href="#xmlrenderer">XMLRenderer</a></li>
|
||||||
|
<li><a href="#templatehtmlrenderer">TemplateHTMLRenderer</a></li>
|
||||||
|
<li><a href="#statichtmlrenderer">StaticHTMLRenderer</a></li>
|
||||||
|
<li><a href="#htmlformrenderer">HTMLFormRenderer</a></li>
|
||||||
|
<li><a href="#browsableapirenderer">BrowsableAPIRenderer</a></li>
|
||||||
|
<li><a href="#multipartrenderer">MultiPartRenderer</a></li>
|
||||||
|
<li class="main"><a href="#custom-renderers">Custom renderers</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="#messagepack">MessagePack</a></li>
|
||||||
|
<li><a href="#csv">CSV</a></li>
|
||||||
|
<li><a href="#ultrajson">UltraJSON</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><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></p>
|
||||||
|
<h1 id="renderers">Renderers</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/dev/ref/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">How the renderer is determined</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.html">content negotiation</a>.</p>
|
||||||
|
<h2 id="setting-the-renderers">Setting the renderers</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>YAML</code> as the main media type and also include the self describing API.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_RENDERER_CLASSES': (
|
||||||
|
'rest_framework.renderers.YAMLRenderer',
|
||||||
|
'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 class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from rest_framework.renderers import JSONRenderer, YAMLRenderer
|
||||||
|
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 or YAML.
|
||||||
|
"""
|
||||||
|
renderer_classes = (JSONRenderer, YAMLRenderer)
|
||||||
|
|
||||||
|
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 class="prettyprint lang-py"><code>@api_view(['GET'])
|
||||||
|
@renderer_classes((JSONRenderer, JSONPRenderer))
|
||||||
|
def user_count_view(request, format=None):
|
||||||
|
"""
|
||||||
|
A view that returns the count of active users, in JSON or JSONp.
|
||||||
|
"""
|
||||||
|
user_count = User.objects.filter(active=True).count()
|
||||||
|
content = {'user_count': user_count}
|
||||||
|
return Response(content)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="ordering-of-renderer-classes">Ordering of renderer classes</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">API Reference</h1>
|
||||||
|
<h2 id="jsonrenderer">JSONRenderer</h2>
|
||||||
|
<p>Renders the request data into <code>JSON</code>, using utf-8 encoding.</p>
|
||||||
|
<p>Note that non-ascii characters will be rendered using JSON's <code>\uXXXX</code> character escape. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{"unicode black star": "\u2605"}
|
||||||
|
</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 class="prettyprint lang-py"><code>{
|
||||||
|
"unicode black star": "\u2605"
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<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="unicodejsonrenderer">UnicodeJSONRenderer</h2>
|
||||||
|
<p>Renders the request data into <code>JSON</code>, using utf-8 encoding.</p>
|
||||||
|
<p>Note that non-ascii characters will not be character escaped. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{"unicode black star": "★"}
|
||||||
|
</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 class="prettyprint lang-py"><code>{
|
||||||
|
"unicode black star": "★"
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Both the <code>JSONRenderer</code> and <code>UnicodeJSONRenderer</code> styles conform to <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>, and are syntactically valid JSON.</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="jsonprenderer">JSONPRenderer</h2>
|
||||||
|
<p>Renders the request data into <code>JSONP</code>. The <code>JSONP</code> media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a <code>JSON</code> response in a javascript callback.</p>
|
||||||
|
<p>The javascript callback function must be set by the client including a <code>callback</code> URL query parameter. For example <code>http://example.com/api/users?callback=jsonpCallback</code>. If the callback function is not explicitly set by the client it will default to <code>'callback'</code>.</p>
|
||||||
|
<p><strong>Note</strong>: If you require cross-domain AJAX requests, you may want to consider 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="../topics/ajax-csrf-cors.html">CORS documentation</a> for more details.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>application/javascript</code></p>
|
||||||
|
<p><strong>.format</strong>: <code>'.jsonp'</code></p>
|
||||||
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
||||||
|
<h2 id="yamlrenderer">YAMLRenderer</h2>
|
||||||
|
<p>Renders the request data into <code>YAML</code>. </p>
|
||||||
|
<p>Requires the <code>pyyaml</code> package to be installed.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>application/yaml</code></p>
|
||||||
|
<p><strong>.format</strong>: <code>'.yaml'</code></p>
|
||||||
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
||||||
|
<h2 id="xmlrenderer">XMLRenderer</h2>
|
||||||
|
<p>Renders REST framework's default style of <code>XML</code> response content.</p>
|
||||||
|
<p>Note that the <code>XML</code> markup language is used typically used as the base language for more strictly defined domain-specific languages, such as <code>RSS</code>, <code>Atom</code>, and <code>XHTML</code>.</p>
|
||||||
|
<p>If you are considering using <code>XML</code> for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.</p>
|
||||||
|
<p><strong>.media_type</strong>: <code>application/xml</code></p>
|
||||||
|
<p><strong>.format</strong>: <code>'.xml'</code></p>
|
||||||
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
||||||
|
<h2 id="templatehtmlrenderer">TemplateHTMLRenderer</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 class="prettyprint lang-py"><code>class UserDetail(generics.RetrieveUserAPIView):
|
||||||
|
"""
|
||||||
|
A view that returns a templated HTML representations 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><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">StaticHTMLRenderer</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>TemplateHTMLRenderer</code>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><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>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><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="htmlformrenderer">HTMLFormRenderer</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 or an submit actions, as you'll probably need those to include the desired method and URL. Also note that the <code>HTMLFormRenderer</code> does not yet support including field error messages.</p>
|
||||||
|
<p>Note that the template used by the <code>HTMLFormRenderer</code> class, and the context submitted to it <strong>may be subject to change</strong>. If you need to use this renderer class it is advised that you either make a local copy of the class and templates, or follow the release note on REST framework upgrades closely.</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/form.html'</code></p>
|
||||||
|
<h2 id="browsableapirenderer">BrowsableAPIRenderer</h2>
|
||||||
|
<p>Renders data into HTML for the Browsable API. 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">Customizing BrowsableAPIRenderer</h4>
|
||||||
|
<p>By default the response content will be rendered with the highest priority renderer apart from <code>BrowseableAPIRenderer</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 class="prettyprint lang-py"><code>class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
|
||||||
|
def get_default_renderer(self, view):
|
||||||
|
return JSONRenderer()
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="multipartrenderer">MultiPartRenderer</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.html">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">Custom renderers</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"><code>data</code></h3>
|
||||||
|
<p>The request data, as set by the <code>Response()</code> instantiation.</p>
|
||||||
|
<h3 id="media_typenone"><code>media_type=None</code></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"><code>renderer_context=None</code></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">Example</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 class="prettyprint lang-py"><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">Setting the character set</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 class="prettyprint lang-py"><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 class="prettyprint lang-py"><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">Advanced renderer usage</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">Varying behaviour by media type</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 class="prettyprint lang-py"><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">Underspecifying the media type</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 class="prettyprint lang-py"><code>return Response(data, content_type='image/png')
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="designing-your-media-types">Designing your media types</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">HTML error views</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/dev/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">Third party packages</h1>
|
||||||
|
<p>The following third party packages are also available.</p>
|
||||||
|
<h2 id="messagepack">MessagePack</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">CSV</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">UltraJSON</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>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
321
api-guide/requests.html
Normal file
|
@ -0,0 +1,321 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Requests</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Requests, Request parsing, Authentication, Browser enhancements, Standard HttpRequest attributes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="requests-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 " href="../api-guide/responses.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/6-viewsets-and-routers.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#requests">Requests</a></li>
|
||||||
|
<li class="main"><a href="#request-parsing">Request parsing</a></li>
|
||||||
|
<li><a href="#data">.DATA</a></li>
|
||||||
|
<li><a href="#files">.FILES</a></li>
|
||||||
|
<li><a href="#query_params">.QUERY_PARAMS</a></li>
|
||||||
|
<li><a href="#parsers">.parsers</a></li>
|
||||||
|
<li class="main"><a href="#authentication">Authentication</a></li>
|
||||||
|
<li><a href="#user">.user</a></li>
|
||||||
|
<li><a href="#auth">.auth</a></li>
|
||||||
|
<li><a href="#authenticators">.authenticators</a></li>
|
||||||
|
<li class="main"><a href="#browser-enhancements">Browser enhancements</a></li>
|
||||||
|
<li><a href="#method">.method</a></li>
|
||||||
|
<li><a href="#content_type">.content_type</a></li>
|
||||||
|
<li><a href="#stream">.stream</a></li>
|
||||||
|
<li class="main"><a href="#standard-httprequest-attributes">Standard HttpRequest attributes</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/request.py"><span class="label label-info">request.py</span></a></p>
|
||||||
|
<h1 id="requests">Requests</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>If you're doing REST-based web service stuff ... you should ignore request.POST.</p>
|
||||||
|
<p>— Malcom Tredinnick, <a href="https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion">Django developers group</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>REST framework's <code>Request</code> class extends the standard <code>HttpRequest</code>, adding support for REST framework's flexible request parsing and request authentication.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="request-parsing">Request parsing</h1>
|
||||||
|
<p>REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.</p>
|
||||||
|
<h2 id="data">.DATA</h2>
|
||||||
|
<p><code>request.DATA</code> returns the parsed content of the request body. This is similar to the standard <code>request.POST</code> attribute except that:</p>
|
||||||
|
<ul>
|
||||||
|
<li>It supports parsing the content of HTTP methods other than <code>POST</code>, meaning that you can access the content of <code>PUT</code> and <code>PATCH</code> requests.</li>
|
||||||
|
<li>It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.</li>
|
||||||
|
</ul>
|
||||||
|
<p>For more details see the <a href="parsers.html">parsers documentation</a>.</p>
|
||||||
|
<h2 id="files">.FILES</h2>
|
||||||
|
<p><code>request.FILES</code> returns any uploaded files that may be present in the content of the request body. This is the same as the standard <code>HttpRequest</code> behavior, except that the same flexible request parsing is used for <code>request.DATA</code>.</p>
|
||||||
|
<p>For more details see the <a href="parsers.html">parsers documentation</a>.</p>
|
||||||
|
<h2 id="query_params">.QUERY_PARAMS</h2>
|
||||||
|
<p><code>request.QUERY_PARAMS</code> is a more correctly named synonym for <code>request.GET</code>.</p>
|
||||||
|
<p>For clarity inside your code, we recommend using <code>request.QUERY_PARAMS</code> instead of the usual <code>request.GET</code>, as <em>any</em> HTTP method type may include query parameters.</p>
|
||||||
|
<h2 id="parsers">.parsers</h2>
|
||||||
|
<p>The <code>APIView</code> class or <code>@api_view</code> decorator will ensure that this property is automatically set to a list of <code>Parser</code> instances, based on the <code>parser_classes</code> set on the view or based on the <code>DEFAULT_PARSER_CLASSES</code> setting.</p>
|
||||||
|
<p>You won't typically need to access this property.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note:</strong> If a client sends malformed content, then accessing <code>request.DATA</code> or <code>request.FILES</code> may raise a <code>ParseError</code>. By default REST framework's <code>APIView</code> class or <code>@api_view</code> decorator will catch the error and return a <code>400 Bad Request</code> response.</p>
|
||||||
|
<p>If a client sends a request with a content-type that cannot be parsed then a <code>UnsupportedMediaType</code> exception will be raised, which by default will be caught and return a <code>415 Unsupported Media Type</code> response.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="authentication">Authentication</h1>
|
||||||
|
<p>REST framework provides flexible, per-request authentication, that gives you the ability to:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Use different authentication policies for different parts of your API.</li>
|
||||||
|
<li>Support the use of multiple authentication policies.</li>
|
||||||
|
<li>Provide both user and token information associated with the incoming request.</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="user">.user</h2>
|
||||||
|
<p><code>request.user</code> typically returns an instance of <code>django.contrib.auth.models.User</code>, although the behavior depends on the authentication policy being used.</p>
|
||||||
|
<p>If the request is unauthenticated the default value of <code>request.user</code> is an instance of <code>django.contrib.auth.models.AnonymousUser</code>.</p>
|
||||||
|
<p>For more details see the <a href="authentication.html">authentication documentation</a>.</p>
|
||||||
|
<h2 id="auth">.auth</h2>
|
||||||
|
<p><code>request.auth</code> returns any additional authentication context. The exact behavior of <code>request.auth</code> depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.</p>
|
||||||
|
<p>If the request is unauthenticated, or if no additional context is present, the default value of <code>request.auth</code> is <code>None</code>.</p>
|
||||||
|
<p>For more details see the <a href="authentication.html">authentication documentation</a>.</p>
|
||||||
|
<h2 id="authenticators">.authenticators</h2>
|
||||||
|
<p>The <code>APIView</code> class or <code>@api_view</code> decorator will ensure that this property is automatically set to a list of <code>Authentication</code> instances, based on the <code>authentication_classes</code> set on the view or based on the <code>DEFAULT_AUTHENTICATORS</code> setting.</p>
|
||||||
|
<p>You won't typically need to access this property.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="browser-enhancements">Browser enhancements</h1>
|
||||||
|
<p>REST framework supports a few browser enhancements such as browser-based <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> forms.</p>
|
||||||
|
<h2 id="method">.method</h2>
|
||||||
|
<p><code>request.method</code> returns the <strong>uppercased</strong> string representation of the request's HTTP method.</p>
|
||||||
|
<p>Browser-based <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> forms are transparently supported.</p>
|
||||||
|
<p>For more information see the <a href="../topics/browser-enhancements.html">browser enhancements documentation</a>. </p>
|
||||||
|
<h2 id="content_type">.content_type</h2>
|
||||||
|
<p><code>request.content_type</code>, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided.</p>
|
||||||
|
<p>You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.</p>
|
||||||
|
<p>If you do need to access the content type of the request you should use the <code>.content_type</code> property in preference to using <code>request.META.get('HTTP_CONTENT_TYPE')</code>, as it provides transparent support for browser-based non-form content.</p>
|
||||||
|
<p>For more information see the <a href="../topics/browser-enhancements.html">browser enhancements documentation</a>. </p>
|
||||||
|
<h2 id="stream">.stream</h2>
|
||||||
|
<p><code>request.stream</code> returns a stream representing the content of the request body.</p>
|
||||||
|
<p>You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.</p>
|
||||||
|
<p>If you do need to access the raw content directly, you should use the <code>.stream</code> property in preference to using <code>request.content</code>, as it provides transparent support for browser-based non-form content.</p>
|
||||||
|
<p>For more information see the <a href="../topics/browser-enhancements.html">browser enhancements documentation</a>. </p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="standard-httprequest-attributes">Standard HttpRequest attributes</h1>
|
||||||
|
<p>As REST framework's <code>Request</code> extends Django's <code>HttpRequest</code>, all the other standard attributes and methods are also available. For example the <code>request.META</code> and <code>request.session</code> dictionaries are available as normal.</p>
|
||||||
|
<p>Note that due to implementation reasons the <code>Request</code> class does not inherit from <code>HttpRequest</code> class, but instead extends the class using composition.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
304
api-guide/responses.html
Normal file
|
@ -0,0 +1,304 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Responses</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Responses, Creating responses, Attributes, Standard HttpResponse attributes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="responses-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 " href="../api-guide/views.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/requests.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#responses">Responses</a></li>
|
||||||
|
<li class="main"><a href="#creating-responses">Creating responses</a></li>
|
||||||
|
<li><a href="#response()">Response()</a></li>
|
||||||
|
<li class="main"><a href="#attributes">Attributes</a></li>
|
||||||
|
<li><a href="#data">.data</a></li>
|
||||||
|
<li><a href="#status_code">.status_code</a></li>
|
||||||
|
<li><a href="#content">.content</a></li>
|
||||||
|
<li><a href="#template_name">.template_name</a></li>
|
||||||
|
<li><a href="#accepted_renderer">.accepted_renderer</a></li>
|
||||||
|
<li><a href="#accepted_media_type">.accepted_media_type</a></li>
|
||||||
|
<li><a href="#renderer_context">.renderer_context</a></li>
|
||||||
|
<li class="main"><a href="#standard-httpresponse-attributes">Standard HttpResponse attributes</a></li>
|
||||||
|
<li><a href="#render()">.render()</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/response.py"><span class="label label-info">response.py</span></a></p>
|
||||||
|
<h1 id="responses">Responses</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.</p>
|
||||||
|
<p>— <a href="https://docs.djangoproject.com/en/dev/ref/template-response/">Django documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>REST framework supports HTTP content negotiation by providing a <code>Response</code> class which allows you to return content that can be rendered into multiple content types, depending on the client request.</p>
|
||||||
|
<p>The <code>Response</code> class subclasses Django's <code>SimpleTemplateResponse</code>. <code>Response</code> objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.</p>
|
||||||
|
<p>There's no requirement for you to use the <code>Response</code> class, you can also return regular <code>HttpResponse</code> or <code>StreamingHttpResponse</code> objects from your views if required. Using the <code>Response</code> class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.</p>
|
||||||
|
<p>Unless you want to heavily customize REST framework for some reason, you should always use an <code>APIView</code> class or <code>@api_view</code> function for views that return <code>Response</code> objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="creating-responses">Creating responses</h1>
|
||||||
|
<h2 id="response">Response()</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>Response(data, status=None, template_name=None, headers=None, content_type=None)</code></p>
|
||||||
|
<p>Unlike regular <code>HttpResponse</code> objects, you do not instantiate <code>Response</code> objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.</p>
|
||||||
|
<p>The renderers used by the <code>Response</code> class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the <code>Response</code> object.</p>
|
||||||
|
<p>You can use REST framework's <code>Serializer</code> classes to perform this data serialization, or use your own custom serialization.</p>
|
||||||
|
<p>Arguments:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>data</code>: The serialized data for the response.</li>
|
||||||
|
<li><code>status</code>: A status code for the response. Defaults to 200. See also <a href="status-codes.html">status codes</a>.</li>
|
||||||
|
<li><code>template_name</code>: A template name to use if <code>HTMLRenderer</code> is selected.</li>
|
||||||
|
<li><code>headers</code>: A dictionary of HTTP headers to use in the response.</li>
|
||||||
|
<li><code>content_type</code>: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h1 id="attributes">Attributes</h1>
|
||||||
|
<h2 id="data">.data</h2>
|
||||||
|
<p>The unrendered content of a <code>Request</code> object.</p>
|
||||||
|
<h2 id="status_code">.status_code</h2>
|
||||||
|
<p>The numeric status code of the HTTP response.</p>
|
||||||
|
<h2 id="content">.content</h2>
|
||||||
|
<p>The rendered content of the response. The <code>.render()</code> method must have been called before <code>.content</code> can be accessed.</p>
|
||||||
|
<h2 id="template_name">.template_name</h2>
|
||||||
|
<p>The <code>template_name</code>, if supplied. Only required if <code>HTMLRenderer</code> or some other custom template renderer is the accepted renderer for the response.</p>
|
||||||
|
<h2 id="accepted_renderer">.accepted_renderer</h2>
|
||||||
|
<p>The renderer instance that will be used to render the response.</p>
|
||||||
|
<p>Set automatically by the <code>APIView</code> or <code>@api_view</code> immediately before the response is returned from the view.</p>
|
||||||
|
<h2 id="accepted_media_type">.accepted_media_type</h2>
|
||||||
|
<p>The media type that was selected by the content negotiation stage.</p>
|
||||||
|
<p>Set automatically by the <code>APIView</code> or <code>@api_view</code> immediately before the response is returned from the view.</p>
|
||||||
|
<h2 id="renderer_context">.renderer_context</h2>
|
||||||
|
<p>A dictionary of additional context information that will be passed to the renderer's <code>.render()</code> method.</p>
|
||||||
|
<p>Set automatically by the <code>APIView</code> or <code>@api_view</code> immediately before the response is returned from the view.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="standard-httpresponse-attributes">Standard HttpResponse attributes</h1>
|
||||||
|
<p>The <code>Response</code> class extends <code>SimpleTemplateResponse</code>, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>response = Response()
|
||||||
|
response['Cache-Control'] = 'no-cache'
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="render">.render()</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>.render()</code></p>
|
||||||
|
<p>As with any other <code>TemplateResponse</code>, this method is called to render the serialized data of the response into the final response content. When <code>.render()</code> is called, the response content will be set to the result of calling the <code>.render(data, accepted_media_type, renderer_context)</code> method on the <code>accepted_renderer</code> instance.</p>
|
||||||
|
<p>You won't typically need to call <code>.render()</code> yourself, as it's handled by Django's standard response cycle.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
279
api-guide/reverse.html
Normal file
|
@ -0,0 +1,279 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Returning URLs</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Returning URLs">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="reverse-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 " href="../api-guide/exceptions.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/format-suffixes.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#returning-urls">Returning URLs</a></li>
|
||||||
|
<li><a href="#reverse">reverse</a></li>
|
||||||
|
<li><a href="#reverse_lazy">reverse_lazy</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/reverse.py"><span class="label label-info">reverse.py</span></a></p>
|
||||||
|
<h1 id="returning-urls">Returning URLs</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.</p>
|
||||||
|
<p>— Roy Fielding, <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5">Architectural Styles and the Design of Network-based Software Architectures</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as <code>http://example.com/foobar</code>, rather than returning relative URIs, such as <code>/foobar</code>.</p>
|
||||||
|
<p>The advantages of doing so are:</p>
|
||||||
|
<ul>
|
||||||
|
<li>It's more explicit.</li>
|
||||||
|
<li>It leaves less work for your API clients.</li>
|
||||||
|
<li>There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.</li>
|
||||||
|
<li>It makes it easy to do things like markup HTML representations with hyperlinks.</li>
|
||||||
|
</ul>
|
||||||
|
<p>REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.</p>
|
||||||
|
<p>There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.</p>
|
||||||
|
<h2 id="reverse">reverse</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>reverse(viewname, *args, **kwargs)</code></p>
|
||||||
|
<p>Has the same behavior as <a href="https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse"><code>django.core.urlresolvers.reverse</code></a>, except that it returns a fully qualified URL, using the request to determine the host and port.</p>
|
||||||
|
<p>You should <strong>include the request as a keyword argument</strong> to the function, for example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.reverse import reverse
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
from django.utils.timezone import now
|
||||||
|
|
||||||
|
class APIRootView(APIView):
|
||||||
|
def get(self, request):
|
||||||
|
year = now().year
|
||||||
|
data = {
|
||||||
|
...
|
||||||
|
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||||
|
}
|
||||||
|
return Response(data)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="reverse_lazy">reverse_lazy</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>reverse_lazy(viewname, *args, **kwargs)</code></p>
|
||||||
|
<p>Has the same behavior as <a href="https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy"><code>django.core.urlresolvers.reverse_lazy</code></a>, except that it returns a fully qualified URL, using the request to determine the host and port.</p>
|
||||||
|
<p>As with the <code>reverse</code> function, you should <strong>include the request as a keyword argument</strong> to the function, for example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>api_root = reverse_lazy('api-root', request=request)
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
369
api-guide/routers.html
Normal file
|
@ -0,0 +1,369 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Routers</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Routers, API Guide, Custom Routers">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="routers-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 " href="../api-guide/parsers.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/viewsets.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#routers">Routers</a></li>
|
||||||
|
<li><a href="#usage">Usage</a></li>
|
||||||
|
<li class="main"><a href="#api-guide">API Guide</a></li>
|
||||||
|
<li><a href="#simplerouter">SimpleRouter</a></li>
|
||||||
|
<li><a href="#defaultrouter">DefaultRouter</a></li>
|
||||||
|
<li class="main"><a href="#custom-routers">Custom Routers</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li><a href="#advanced-custom-routers">Advanced custom routers</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/routers.py"><span class="label label-info">routers.py</span></a></p>
|
||||||
|
<h1 id="routers">Routers</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.</p>
|
||||||
|
<p>— <a href="http://guides.rubyonrails.org/routing.html">Ruby on Rails Documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.</p>
|
||||||
|
<p>REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.</p>
|
||||||
|
<h2 id="usage">Usage</h2>
|
||||||
|
<p>Here's an example of a simple URL conf, that uses <code>DefaultRouter</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import routers
|
||||||
|
|
||||||
|
router = routers.SimpleRouter()
|
||||||
|
router.register(r'users', UserViewSet)
|
||||||
|
router.register(r'accounts', AccountViewSet)
|
||||||
|
urlpatterns = router.urls
|
||||||
|
</code></pre>
|
||||||
|
<p>There are two mandatory arguments to the <code>register()</code> method:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>prefix</code> - The URL prefix to use for this set of routes.</li>
|
||||||
|
<li><code>viewset</code> - The viewset class.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Optionally, you may also specify an additional argument:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>base_name</code> - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the <code>model</code> or <code>queryset</code> attribute on the viewset, if it has one. Note that if the viewset does not include a <code>model</code> or <code>queryset</code> attribute then you must set <code>base_name</code> when registering the viewset.</li>
|
||||||
|
</ul>
|
||||||
|
<p>The example above would generate the following URL patterns:</p>
|
||||||
|
<ul>
|
||||||
|
<li>URL pattern: <code>^users/$</code> Name: <code>'user-list'</code></li>
|
||||||
|
<li>URL pattern: <code>^users/{pk}/$</code> Name: <code>'user-detail'</code></li>
|
||||||
|
<li>URL pattern: <code>^accounts/$</code> Name: <code>'account-list'</code></li>
|
||||||
|
<li>URL pattern: <code>^accounts/{pk}/$</code> Name: <code>'account-detail'</code></li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="extra-link-and-actions">Extra link and actions</h3>
|
||||||
|
<p>Any methods on the viewset decorated with <code>@link</code> or <code>@action</code> will also be routed.
|
||||||
|
For example, given a method like this on the <code>UserViewSet</code> class:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from myapp.permissions import IsAdminOrIsSelf
|
||||||
|
from rest_framework.decorators import action
|
||||||
|
|
||||||
|
@action(permission_classes=[IsAdminOrIsSelf])
|
||||||
|
def set_password(self, request, pk=None):
|
||||||
|
...
|
||||||
|
</code></pre>
|
||||||
|
<p>The following URL pattern would additionally be generated:</p>
|
||||||
|
<ul>
|
||||||
|
<li>URL pattern: <code>^users/{pk}/set_password/$</code> Name: <code>'user-set-password'</code></li>
|
||||||
|
</ul>
|
||||||
|
<h1 id="api-guide">API Guide</h1>
|
||||||
|
<h2 id="simplerouter">SimpleRouter</h2>
|
||||||
|
<p>This router includes routes for the standard set of <code>list</code>, <code>create</code>, <code>retrieve</code>, <code>update</code>, <code>partial_update</code> and <code>destroy</code> actions. The viewset can also mark additional methods to be routed, using the <code>@link</code> or <code>@action</code> decorators.</p>
|
||||||
|
<table border=1>
|
||||||
|
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
||||||
|
<tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
||||||
|
<tr><td>POST</td><td>create</td></tr>
|
||||||
|
<tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
||||||
|
<tr><td>PUT</td><td>update</td></tr>
|
||||||
|
<tr><td>PATCH</td><td>partial_update</td></tr>
|
||||||
|
<tr><td>DELETE</td><td>destroy</td></tr>
|
||||||
|
<tr><td rowspan=2>{prefix}/{lookup}/{methodname}/</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
|
||||||
|
<tr><td>POST</td><td>@action decorated method</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>By default the URLs created by <code>SimpleRouter</code> are appended with a trailing slash.
|
||||||
|
This behavior can be modified by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>router = SimpleRouter(trailing_slash=False)
|
||||||
|
</code></pre>
|
||||||
|
<p>Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.</p>
|
||||||
|
<h2 id="defaultrouter">DefaultRouter</h2>
|
||||||
|
<p>This router is similar to <code>SimpleRouter</code> as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional <code>.json</code> style format suffixes.</p>
|
||||||
|
<table border=1>
|
||||||
|
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
||||||
|
<tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
|
||||||
|
<tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
||||||
|
<tr><td>POST</td><td>create</td></tr>
|
||||||
|
<tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
||||||
|
<tr><td>PUT</td><td>update</td></tr>
|
||||||
|
<tr><td>PATCH</td><td>partial_update</td></tr>
|
||||||
|
<tr><td>DELETE</td><td>destroy</td></tr>
|
||||||
|
<tr><td rowspan=2>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
|
||||||
|
<tr><td>POST</td><td>@action decorated method</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p>As with <code>SimpleRouter</code> the trailing slashes on the URL routes can be removed by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>router = DefaultRouter(trailing_slash=False)
|
||||||
|
</code></pre>
|
||||||
|
<h1 id="custom-routers">Custom Routers</h1>
|
||||||
|
<p>Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.</p>
|
||||||
|
<p>The simplest way to implement a custom router is to subclass one of the existing router classes. The <code>.routes</code> attribute is used to template the URL patterns that will be mapped to each viewset. The <code>.routes</code> attribute is a list of <code>Route</code> named tuples.</p>
|
||||||
|
<p>The arguments to the <code>Route</code> named tuple are:</p>
|
||||||
|
<p><strong>url</strong>: A string representing the URL to be routed. May include the following format strings:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>{prefix}</code> - The URL prefix to use for this set of routes.</li>
|
||||||
|
<li><code>{lookup}</code> - The lookup field used to match against a single instance.</li>
|
||||||
|
<li><code>{trailing_slash}</code> - Either a '/' or an empty string, depending on the <code>trailing_slash</code> argument.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>mapping</strong>: A mapping of HTTP method names to the view methods</p>
|
||||||
|
<p><strong>name</strong>: The name of the URL as used in <code>reverse</code> calls. May include the following format string:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>{basename}</code> - The base to use for the URL names that are created.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>initkwargs</strong>: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the <code>suffix</code> argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>The following example will only route to the <code>list</code> and <code>retrieve</code> actions, and does not use the trailing slash convention.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.routers import Route, SimpleRouter
|
||||||
|
|
||||||
|
class ReadOnlyRouter(SimpleRouter):
|
||||||
|
"""
|
||||||
|
A router for read-only APIs, which doesn't use trailing slashes.
|
||||||
|
"""
|
||||||
|
routes = [
|
||||||
|
Route(url=r'^{prefix}$',
|
||||||
|
mapping={'get': 'list'},
|
||||||
|
name='{basename}-list',
|
||||||
|
initkwargs={'suffix': 'List'}),
|
||||||
|
Route(url=r'^{prefix}/{lookup}$',
|
||||||
|
mapping={'get': 'retrieve'},
|
||||||
|
name='{basename}-detail',
|
||||||
|
initkwargs={'suffix': 'Detail'})
|
||||||
|
]
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>SimpleRouter</code> class provides another example of setting the <code>.routes</code> attribute.</p>
|
||||||
|
<h2 id="advanced-custom-routers">Advanced custom routers</h2>
|
||||||
|
<p>If you want to provide totally custom behavior, you can override <code>BaseRouter</code> and override the <code>get_urls(self)</code> method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the <code>self.registry</code> attribute. </p>
|
||||||
|
<p>You may also want to override the <code>get_default_base_name(self, viewset)</code> method, or else always explicitly set the <code>base_name</code> argument when registering your viewsets with the router.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
668
api-guide/serializers.html
Normal file
|
@ -0,0 +1,668 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Serializers</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Serializers, ModelSerializer, HyperlinkedModelSerializer, Advanced serializer usage">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="serializers-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 " href="../api-guide/fields.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/renderers.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#serializers">Serializers</a></li>
|
||||||
|
<li><a href="#declaring-serializers">Declaring Serializers</a></li>
|
||||||
|
<li><a href="#serializing-objects">Serializing objects</a></li>
|
||||||
|
<li><a href="#deserializing-objects">Deserializing objects</a></li>
|
||||||
|
<li><a href="#validation">Validation</a></li>
|
||||||
|
<li><a href="#saving-object-state">Saving object state</a></li>
|
||||||
|
<li><a href="#dealing-with-nested-objects">Dealing with nested objects</a></li>
|
||||||
|
<li><a href="#dealing-with-multiple-objects">Dealing with multiple objects</a></li>
|
||||||
|
<li><a href="#including-extra-context">Including extra context</a></li>
|
||||||
|
<li class="main"><a href="#modelserializer">ModelSerializer</a></li>
|
||||||
|
<li><a href="#specifying-which-fields-should-be-included">Specifying which fields should be included</a></li>
|
||||||
|
<li><a href="#specifying-nested-serialization">Specifying nested serialization</a></li>
|
||||||
|
<li><a href="#specifying-which-fields-should-be-read-only">Specifying which fields should be read-only</a></li>
|
||||||
|
<li><a href="#specifying-fields-explicitly">Specifying fields explicitly</a></li>
|
||||||
|
<li><a href="#relational-fields">Relational fields</a></li>
|
||||||
|
<li class="main"><a href="#hyperlinkedmodelserializer">HyperlinkedModelSerializer</a></li>
|
||||||
|
<li><a href="#how-hyperlinked-views-are-determined">How hyperlinked views are determined</a></li>
|
||||||
|
<li class="main"><a href="#advanced-serializer-usage">Advanced serializer usage</a></li>
|
||||||
|
<li><a href="#dynamically-modifying-fields">Dynamically modifying fields</a></li>
|
||||||
|
<li><a href="#customising-the-default-fields">Customising the default fields</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/serializers.py"><span class="label label-info">serializers.py</span></a></p>
|
||||||
|
<h1 id="serializers">Serializers</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Expanding the usefulness of the serializers is something that we would
|
||||||
|
like to address. However, it's not a trivial problem, and it
|
||||||
|
will take some serious design work.</p>
|
||||||
|
<p>— Russell Keith-Magee, <a href="https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion">Django users group</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into <code>JSON</code>, <code>XML</code> or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.</p>
|
||||||
|
<p>REST framework's serializers work very similarly to Django's <code>Form</code> and <code>ModelForm</code> classes. It provides a <code>Serializer</code> class which gives you a powerful, generic way to control the output of your responses, as well as a <code>ModelSerializer</code> class which provides a useful shortcut for creating serializers that deal with model instances and querysets.</p>
|
||||||
|
<h2 id="declaring-serializers">Declaring Serializers</h2>
|
||||||
|
<p>Let's start by creating a simple object we can use for example purposes:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class Comment(object):
|
||||||
|
def __init__(self, email, content, created=None):
|
||||||
|
self.email = email
|
||||||
|
self.content = content
|
||||||
|
self.created = created or datetime.datetime.now()
|
||||||
|
|
||||||
|
comment = Comment(email='leila@example.com', content='foo bar')
|
||||||
|
</code></pre>
|
||||||
|
<p>We'll declare a serializer that we can use to serialize and deserialize <code>Comment</code> objects.</p>
|
||||||
|
<p>Declaring a serializer looks very similar to declaring a form:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import serializers
|
||||||
|
|
||||||
|
class CommentSerializer(serializers.Serializer):
|
||||||
|
email = serializers.EmailField()
|
||||||
|
content = serializers.CharField(max_length=200)
|
||||||
|
created = serializers.DateTimeField()
|
||||||
|
|
||||||
|
def restore_object(self, attrs, instance=None):
|
||||||
|
"""
|
||||||
|
Given a dictionary of deserialized field values, either update
|
||||||
|
an existing model instance, or create a new model instance.
|
||||||
|
"""
|
||||||
|
if instance is not None:
|
||||||
|
instance.email = attrs.get('email', instance.email)
|
||||||
|
instance.content = attrs.get('content', instance.content)
|
||||||
|
instance.created = attrs.get('created', instance.created)
|
||||||
|
return instance
|
||||||
|
return Comment(**attrs)
|
||||||
|
</code></pre>
|
||||||
|
<p>The first part of serializer class defines the fields that get serialized/deserialized. The <code>restore_object</code> method defines how fully fledged instances get created when deserializing data.</p>
|
||||||
|
<p>The <code>restore_object</code> method is optional, and is only required if we want our serializer to support deserialization into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items.</p>
|
||||||
|
<h2 id="serializing-objects">Serializing objects</h2>
|
||||||
|
<p>We can now use <code>CommentSerializer</code> to serialize a comment, or list of comments. Again, using the <code>Serializer</code> class looks a lot like using a <code>Form</code> class.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(comment)
|
||||||
|
serializer.data
|
||||||
|
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
|
||||||
|
</code></pre>
|
||||||
|
<p>At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into <code>json</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.renderers import JSONRenderer
|
||||||
|
|
||||||
|
json = JSONRenderer().render(serializer.data)
|
||||||
|
json
|
||||||
|
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
|
||||||
|
</code></pre>
|
||||||
|
<h3 id="customizing-field-representation">Customizing field representation</h3>
|
||||||
|
<p>Sometimes when serializing objects, you may not want to represent everything exactly the way it is in your model.</p>
|
||||||
|
<p>If you need to customize the serialized value of a particular field, you can do this by creating a <code>transform_<fieldname></code> method. For example if you needed to render some markdown from a text field:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>description = serializers.TextField()
|
||||||
|
description_html = serializers.TextField(source='description', read_only=True)
|
||||||
|
|
||||||
|
def transform_description_html(self, obj, value):
|
||||||
|
from django.contrib.markup.templatetags.markup import markdown
|
||||||
|
return markdown(value)
|
||||||
|
</code></pre>
|
||||||
|
<p>These methods are essentially the reverse of <code>validate_<fieldname></code> (see <em>Validation</em> below.)</p>
|
||||||
|
<h2 id="deserializing-objects">Deserializing objects</h2>
|
||||||
|
<p>Deserialization is similar. First we parse a stream into Python native datatypes... </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from StringIO import StringIO
|
||||||
|
from rest_framework.parsers import JSONParser
|
||||||
|
|
||||||
|
stream = StringIO(json)
|
||||||
|
data = JSONParser().parse(stream)
|
||||||
|
</code></pre>
|
||||||
|
<p>...then we restore those native datatypes into a fully populated object instance.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(data=data)
|
||||||
|
serializer.is_valid()
|
||||||
|
# True
|
||||||
|
serializer.object
|
||||||
|
# <Comment object at 0x10633b2d0>
|
||||||
|
</code></pre>
|
||||||
|
<p>When deserializing data, we can either create a new instance, or update an existing instance.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(data=data) # Create new instance
|
||||||
|
serializer = CommentSerializer(comment, data=data) # Update `instance`
|
||||||
|
</code></pre>
|
||||||
|
<p>By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the <code>partial</code> argument in order to allow partial updates.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `instance` with partial data
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="validation">Validation</h2>
|
||||||
|
<p>When deserializing data, you always need to call <code>is_valid()</code> before attempting to access the deserialized object. If any validation errors occur, the <code>.errors</code> property will contain a dictionary representing the resulting error messages. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
|
||||||
|
serializer.is_valid()
|
||||||
|
# False
|
||||||
|
serializer.errors
|
||||||
|
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
|
||||||
|
</code></pre>
|
||||||
|
<p>Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The <code>non_field_errors</code> key may also be present, and will list any general validation errors.</p>
|
||||||
|
<p>When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.</p>
|
||||||
|
<h4 id="field-level-validation">Field-level validation</h4>
|
||||||
|
<p>You can specify custom field-level validation by adding <code>.validate_<fieldname></code> methods to your <code>Serializer</code> subclass. These are analogous to <code>.clean_<fieldname></code> methods on Django forms, but accept slightly different arguments.</p>
|
||||||
|
<p>They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the <code>source</code> argument to the field, if one was provided).</p>
|
||||||
|
<p>Your <code>validate_<fieldname></code> methods should either just return the <code>attrs</code> dictionary or raise a <code>ValidationError</code>. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import serializers
|
||||||
|
|
||||||
|
class BlogPostSerializer(serializers.Serializer):
|
||||||
|
title = serializers.CharField(max_length=100)
|
||||||
|
content = serializers.CharField()
|
||||||
|
|
||||||
|
def validate_title(self, attrs, source):
|
||||||
|
"""
|
||||||
|
Check that the blog post is about Django.
|
||||||
|
"""
|
||||||
|
value = attrs[source]
|
||||||
|
if "django" not in value.lower():
|
||||||
|
raise serializers.ValidationError("Blog post is not about Django")
|
||||||
|
return attrs
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="object-level-validation">Object-level validation</h4>
|
||||||
|
<p>To do any other validation that requires access to multiple fields, add a method called <code>.validate()</code> to your <code>Serializer</code> subclass. This method takes a single argument, which is the <code>attrs</code> dictionary. It should raise a <code>ValidationError</code> if necessary, or just return <code>attrs</code>. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import serializers
|
||||||
|
|
||||||
|
class EventSerializer(serializers.Serializer):
|
||||||
|
description = serializers.CharField(max_length=100)
|
||||||
|
start = serializers.DateTimeField()
|
||||||
|
finish = serializers.DateTimeField()
|
||||||
|
|
||||||
|
def validate(self, attrs):
|
||||||
|
"""
|
||||||
|
Check that the start is before the stop.
|
||||||
|
"""
|
||||||
|
if attrs['start'] < attrs['finish']:
|
||||||
|
raise serializers.ValidationError("finish must occur after start")
|
||||||
|
return attrs
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="saving-object-state">Saving object state</h2>
|
||||||
|
<p>To save the deserialized objects created by a serializer, call the <code>.save()</code> method:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>if serializer.is_valid():
|
||||||
|
serializer.save()
|
||||||
|
</code></pre>
|
||||||
|
<p>The default behavior of the method is to simply call <code>.save()</code> on the deserialized object instance. You can override the default save behaviour by overriding the <code>.save_object(obj)</code> method on the serializer class.</p>
|
||||||
|
<p>The generic views provided by REST framework call the <code>.save()</code> method when updating or creating entities. </p>
|
||||||
|
<h2 id="dealing-with-nested-objects">Dealing with nested objects</h2>
|
||||||
|
<p>The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.</p>
|
||||||
|
<p>The <code>Serializer</code> class is itself a type of <code>Field</code>, and can be used to represent relationships where one object type is nested inside another.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserSerializer(serializers.Serializer):
|
||||||
|
email = serializers.EmailField()
|
||||||
|
username = serializers.CharField(max_length=100)
|
||||||
|
|
||||||
|
class CommentSerializer(serializers.Serializer):
|
||||||
|
user = UserSerializer()
|
||||||
|
content = serializers.CharField(max_length=200)
|
||||||
|
created = serializers.DateTimeField()
|
||||||
|
</code></pre>
|
||||||
|
<p>If a nested representation may optionally accept the <code>None</code> value you should pass the <code>required=False</code> flag to the nested serializer.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CommentSerializer(serializers.Serializer):
|
||||||
|
user = UserSerializer(required=False) # May be an anonymous user.
|
||||||
|
content = serializers.CharField(max_length=200)
|
||||||
|
created = serializers.DateTimeField()
|
||||||
|
</code></pre>
|
||||||
|
<p>Similarly if a nested representation should be a list of items, you should pass the <code>many=True</code> flag to the nested serialized.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CommentSerializer(serializers.Serializer):
|
||||||
|
user = UserSerializer(required=False)
|
||||||
|
edits = EditItemSerializer(many=True) # A nested list of 'edit' items.
|
||||||
|
content = serializers.CharField(max_length=200)
|
||||||
|
created = serializers.DateTimeField()
|
||||||
|
</code></pre>
|
||||||
|
<p>Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = CommentSerializer(comment, data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
|
||||||
|
serializer.is_valid()
|
||||||
|
# False
|
||||||
|
serializer.errors
|
||||||
|
# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="dealing-with-multiple-objects">Dealing with multiple objects</h2>
|
||||||
|
<p>The <code>Serializer</code> class can also handle serializing or deserializing lists of objects.</p>
|
||||||
|
<h4 id="serializing-multiple-objects">Serializing multiple objects</h4>
|
||||||
|
<p>To serialize a queryset or list of objects instead of a single object instance, you should pass the <code>many=True</code> flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>queryset = Book.objects.all()
|
||||||
|
serializer = BookSerializer(queryset, many=True)
|
||||||
|
serializer.data
|
||||||
|
# [
|
||||||
|
# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
|
||||||
|
# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
|
||||||
|
# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
|
||||||
|
# ]
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="deserializing-multiple-objects-for-creation">Deserializing multiple objects for creation</h4>
|
||||||
|
<p>To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the <code>many=True</code> flag, and pass a list of data to be deserialized.</p>
|
||||||
|
<p>This allows you to write views that create multiple items when a <code>POST</code> request is made.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>data = [
|
||||||
|
{'title': 'The bell jar', 'author': 'Sylvia Plath'},
|
||||||
|
{'title': 'For whom the bell tolls', 'author': 'Ernest Hemingway'}
|
||||||
|
]
|
||||||
|
serializer = BookSerializer(data=data, many=True)
|
||||||
|
serializer.is_valid()
|
||||||
|
# True
|
||||||
|
serializer.save() # `.save()` will be called on each deserialized instance
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="deserializing-multiple-objects-for-update">Deserializing multiple objects for update</h4>
|
||||||
|
<p>You can also deserialize a list of objects as part of a bulk update of multiple existing items.
|
||||||
|
In this case you need to supply both an existing list or queryset of items, as well as a list of data to update those items with.</p>
|
||||||
|
<p>This allows you to write views that update or create multiple items when a <code>PUT</code> request is made.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># Capitalizing the titles of the books
|
||||||
|
queryset = Book.objects.all()
|
||||||
|
data = [
|
||||||
|
{'id': 3, 'title': 'The Bell Jar', 'author': 'Sylvia Plath'},
|
||||||
|
{'id': 4, 'title': 'For Whom the Bell Tolls', 'author': 'Ernest Hemingway'}
|
||||||
|
]
|
||||||
|
serializer = BookSerializer(queryset, data=data, many=True)
|
||||||
|
serializer.is_valid()
|
||||||
|
# True
|
||||||
|
serializer.save() # `.save()` will be called on each updated or newly created instance.
|
||||||
|
</code></pre>
|
||||||
|
<p>By default bulk updates will be limited to updating instances that already exist in the provided queryset.</p>
|
||||||
|
<p>When performing a bulk update you may want to allow new items to be created, and missing items to be deleted. To do so, pass <code>allow_add_remove=True</code> to the serializer.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
|
||||||
|
serializer.is_valid()
|
||||||
|
# True
|
||||||
|
serializer.save() # `.save()` will be called on updated or newly created instances.
|
||||||
|
# `.delete()` will be called on any other items in the `queryset`.
|
||||||
|
</code></pre>
|
||||||
|
<p>Passing <code>allow_add_remove=True</code> ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects.</p>
|
||||||
|
<h4 id="how-identity-is-determined-when-performing-bulk-updates">How identity is determined when performing bulk updates</h4>
|
||||||
|
<p>Performing a bulk update is slightly more complicated than performing a bulk creation, because the serializer needs a way to determine how the items in the incoming data should be matched against the existing object instances.</p>
|
||||||
|
<p>By default the serializer class will use the <code>id</code> key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the <code>get_identity</code> method on the <code>Serializer</code> class. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.Serializer):
|
||||||
|
slug = serializers.CharField(max_length=100)
|
||||||
|
created = serializers.DateTimeField()
|
||||||
|
... # Various other fields
|
||||||
|
|
||||||
|
def get_identity(self, data):
|
||||||
|
"""
|
||||||
|
This hook is required for bulk update.
|
||||||
|
We need to override the default, to use the slug as the identity.
|
||||||
|
|
||||||
|
Note that the data has not yet been validated at this point,
|
||||||
|
so we need to deal gracefully with incorrect datatypes.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return data.get('slug', None)
|
||||||
|
except AttributeError:
|
||||||
|
return None
|
||||||
|
</code></pre>
|
||||||
|
<p>To map the incoming data items to their corresponding object instances, the <code>.get_identity()</code> method will be called both against the incoming data, and against the serialized representation of the existing objects.</p>
|
||||||
|
<h2 id="including-extra-context">Including extra context</h2>
|
||||||
|
<p>There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.</p>
|
||||||
|
<p>You can provide arbitrary additional context by passing a <code>context</code> argument when instantiating the serializer. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = AccountSerializer(account, context={'request': request})
|
||||||
|
serializer.data
|
||||||
|
# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
|
||||||
|
</code></pre>
|
||||||
|
<p>The context dictionary can be used within any serializer field logic, such as a custom <code>.to_native()</code> method, by accessing the <code>self.context</code> attribute.</p>
|
||||||
|
<p>-</p>
|
||||||
|
<h1 id="modelserializer">ModelSerializer</h1>
|
||||||
|
<p>Often you'll want serializer classes that map closely to model definitions.
|
||||||
|
The <code>ModelSerializer</code> class lets you automatically create a Serializer class with fields that correspond to the Model fields.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
</code></pre>
|
||||||
|
<p>By default, all the model fields on the class will be mapped to corresponding serializer fields.</p>
|
||||||
|
<p>Any relationships such as foreign keys on the model will be mapped to <code>PrimaryKeyRelatedField</code>. Other models fields will be mapped to a corresponding serializer field.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note</strong>: When validation is applied to a <code>ModelSerializer</code>, both the serializer fields, and their corresponding model fields must correctly validate. If you have optional fields on your model, make sure to correctly set <code>blank=True</code> on the model field, as well as setting <code>required=False</code> on the serializer field.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="specifying-which-fields-should-be-included">Specifying which fields should be included</h2>
|
||||||
|
<p>If you only want a subset of the default fields to be used in a model serializer, you can do so using <code>fields</code> or <code>exclude</code> options, just as you would with a <code>ModelForm</code>.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
fields = ('id', 'account_name', 'users', 'created')
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="specifying-nested-serialization">Specifying nested serialization</h2>
|
||||||
|
<p>The default <code>ModelSerializer</code> uses primary keys for relationships, but you can also easily generate nested representations using the <code>depth</code> option:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
fields = ('id', 'account_name', 'users', 'created')
|
||||||
|
depth = 1
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>depth</code> option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.</p>
|
||||||
|
<p>If you want to customize the way the serialization is done (e.g. using <code>allow_add_remove</code>) you'll need to define the field yourself.</p>
|
||||||
|
<h2 id="specifying-which-fields-should-be-read-only">Specifying which fields should be read-only</h2>
|
||||||
|
<p>You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the <code>read_only=True</code> attribute, you may use the <code>read_only_fields</code> Meta option, like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
fields = ('id', 'account_name', 'users', 'created')
|
||||||
|
read_only_fields = ('account_name',)
|
||||||
|
</code></pre>
|
||||||
|
<p>Model fields which have <code>editable=False</code> set, and <code>AutoField</code> fields will be set to read-only by default, and do not need to be added to the <code>read_only_fields</code> option. </p>
|
||||||
|
<h2 id="specifying-fields-explicitly">Specifying fields explicitly</h2>
|
||||||
|
<p>You can add extra fields to a <code>ModelSerializer</code> or override the default fields by declaring fields on the class, just as you would for a <code>Serializer</code> class.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.ModelSerializer):
|
||||||
|
url = serializers.CharField(source='get_absolute_url', read_only=True)
|
||||||
|
groups = serializers.PrimaryKeyRelatedField(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
</code></pre>
|
||||||
|
<p>Extra fields can correspond to any property or callable on the model.</p>
|
||||||
|
<h2 id="relational-fields">Relational fields</h2>
|
||||||
|
<p>When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for <code>ModelSerializer</code> is to use the primary keys of the related instances.</p>
|
||||||
|
<p>Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.</p>
|
||||||
|
<p>For full details see the <a href="relations.html">serializer relations</a> documentation.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="hyperlinkedmodelserializer">HyperlinkedModelSerializer</h1>
|
||||||
|
<p>The <code>HyperlinkedModelSerializer</code> class is similar to the <code>ModelSerializer</code> class except that it uses hyperlinks to represent relationships, rather than primary keys.</p>
|
||||||
|
<p>By default the serializer will include a <code>url</code> field instead of a primary key field.</p>
|
||||||
|
<p>The url field will be represented using a <code>HyperlinkedIdentityField</code> serializer field, and any relationships on the model will be represented using a <code>HyperlinkedRelatedField</code> serializer field.</p>
|
||||||
|
<p>You can explicitly include the primary key by adding it to the <code>fields</code> option, for example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
fields = ('url', 'id', 'account_name', 'users', 'created')
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="how-hyperlinked-views-are-determined">How hyperlinked views are determined</h2>
|
||||||
|
<p>There needs to be a way of determining which views should be used for hyperlinking to model instances.</p>
|
||||||
|
<p>By default hyperlinks are expected to correspond to a view name that matches the style <code>'{model_name}-detail'</code>, and looks up the instance by a <code>pk</code> keyword argument.</p>
|
||||||
|
<p>You can change the field that is used for object lookups by setting the <code>lookup_field</code> option. The value of this option should correspond both with a kwarg in the URL conf, and with a field on the model. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
fields = ('url', 'account_name', 'users', 'created')
|
||||||
|
lookup_field = 'slug'
|
||||||
|
</code></pre>
|
||||||
|
<p>Not that the <code>lookup_field</code> will be used as the default on <em>all</em> hyperlinked fields, including both the URL identity, and any hyperlinked relationships.</p>
|
||||||
|
<p>For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
url = serializers.HyperlinkedIdentityField(
|
||||||
|
view_name='account_detail',
|
||||||
|
lookup_field='account_name'
|
||||||
|
)
|
||||||
|
users = serializers.HyperlinkedRelatedField(
|
||||||
|
view_name='user-detail',
|
||||||
|
lookup_field='username',
|
||||||
|
many=True,
|
||||||
|
read_only=True
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Account
|
||||||
|
fields = ('url', 'account_name', 'users', 'created')
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="advanced-serializer-usage">Advanced serializer usage</h1>
|
||||||
|
<p>You can create customized subclasses of <code>ModelSerializer</code> or <code>HyperlinkedModelSerializer</code> that use a different set of default fields.</p>
|
||||||
|
<p>Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat.</p>
|
||||||
|
<h2 id="dynamically-modifying-fields">Dynamically modifying fields</h2>
|
||||||
|
<p>Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the <code>.fields</code> attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.</p>
|
||||||
|
<p>Modifying the <code>fields</code> argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.</p>
|
||||||
|
<h3 id="example">Example</h3>
|
||||||
|
<p>For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class DynamicFieldsModelSerializer(serializers.ModelSerializer):
|
||||||
|
"""
|
||||||
|
A ModelSerializer that takes an additional `fields` argument that
|
||||||
|
controls which fields should be displayed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
# Don't pass the 'fields' arg up to the superclass
|
||||||
|
fields = kwargs.pop('fields', None)
|
||||||
|
|
||||||
|
# Instantiate the superclass normally
|
||||||
|
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
if fields:
|
||||||
|
# Drop any fields that are not specified in the `fields` argument.
|
||||||
|
allowed = set(fields)
|
||||||
|
existing = set(self.fields.keys())
|
||||||
|
for field_name in existing - allowed:
|
||||||
|
self.fields.pop(field_name)
|
||||||
|
</code></pre>
|
||||||
|
<p>This would then allow you to do the following:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>>>> class UserSerializer(DynamicFieldsModelSerializer):
|
||||||
|
>>> class Meta:
|
||||||
|
>>> model = User
|
||||||
|
>>> fields = ('id', 'username', 'email')
|
||||||
|
>>>
|
||||||
|
>>> print UserSerializer(user)
|
||||||
|
{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
|
||||||
|
>>>
|
||||||
|
>>> print UserSerializer(user, fields=('id', 'email'))
|
||||||
|
{'id': 2, 'email': 'jon@example.com'}
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="customising-the-default-fields">Customising the default fields</h2>
|
||||||
|
<p>The <code>field_mapping</code> attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes. </p>
|
||||||
|
<p>For more advanced customization than simply changing the default serializer class you can override various <code>get_<field_type>_field</code> methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or <code>None</code>.</p>
|
||||||
|
<h3 id="get_pk_field">get_pk_field</h3>
|
||||||
|
<p><strong>Signature</strong>: <code>.get_pk_field(self, model_field)</code></p>
|
||||||
|
<p>Returns the field instance that should be used to represent the pk field.</p>
|
||||||
|
<h3 id="get_nested_field">get_nested_field</h3>
|
||||||
|
<p><strong>Signature</strong>: <code>.get_nested_field(self, model_field, related_model, to_many)</code></p>
|
||||||
|
<p>Returns the field instance that should be used to represent a related field when <code>depth</code> is specified as being non-zero.</p>
|
||||||
|
<p>Note that the <code>model_field</code> argument will be <code>None</code> for reverse relationships. The <code>related_model</code> argument will be the model class for the target of the field. The <code>to_many</code> argument will be a boolean indicating if this is a to-one or to-many relationship.</p>
|
||||||
|
<h3 id="get_related_field">get_related_field</h3>
|
||||||
|
<p><strong>Signature</strong>: <code>.get_related_field(self, model_field, related_model, to_many)</code></p>
|
||||||
|
<p>Returns the field instance that should be used to represent a related field when <code>depth</code> is not specified, or when nested representations are being used and the depth reaches zero.</p>
|
||||||
|
<p>Note that the <code>model_field</code> argument will be <code>None</code> for reverse relationships. The <code>related_model</code> argument will be the model class for the target of the field. The <code>to_many</code> argument will be a boolean indicating if this is a to-one or to-many relationship.</p>
|
||||||
|
<h3 id="get_field">get_field</h3>
|
||||||
|
<p><strong>Signature</strong>: <code>.get_field(self, model_field)</code></p>
|
||||||
|
<p>Returns the field instance that should be used for non-relational, non-pk fields.</p>
|
||||||
|
<h3 id="example_1">Example</h3>
|
||||||
|
<p>The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class NoPKModelSerializer(serializers.ModelSerializer):
|
||||||
|
def get_pk_field(self, model_field):
|
||||||
|
return None
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
468
api-guide/settings.html
Normal file
|
@ -0,0 +1,468 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Settings</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Settings, API Reference">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="settings-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 " href="../topics/documenting-your-api.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/testing.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#settings">Settings</a></li>
|
||||||
|
<li><a href="#accessing-settings">Accessing settings</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#api-policy-settings">API policy settings</a></li>
|
||||||
|
<li><a href="#generic-view-settings">Generic view settings</a></li>
|
||||||
|
<li><a href="#authentication-settings">Authentication settings</a></li>
|
||||||
|
<li><a href="#test-settings">Test settings</a></li>
|
||||||
|
<li><a href="#browser-overrides">Browser overrides</a></li>
|
||||||
|
<li><a href="#date-and-time-formatting">Date and time formatting</a></li>
|
||||||
|
<li><a href="#view-names-and-descriptions">View names and descriptions</a></li>
|
||||||
|
<li><a href="#miscellaneous-settings">Miscellaneous settings</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/settings.py"><span class="label label-info">settings.py</span></a></p>
|
||||||
|
<h1 id="settings">Settings</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Namespaces are one honking great idea - let's do more of those!</p>
|
||||||
|
<p>— <a href="http://www.python.org/dev/peps/pep-0020/">The Zen of Python</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Configuration for REST framework is all namespaced inside a single Django setting, named <code>REST_FRAMEWORK</code>.</p>
|
||||||
|
<p>For example your project's <code>settings.py</code> file might include something like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_RENDERER_CLASSES': (
|
||||||
|
'rest_framework.renderers.YAMLRenderer',
|
||||||
|
),
|
||||||
|
'DEFAULT_PARSER_CLASSES': (
|
||||||
|
'rest_framework.parsers.YAMLParser',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="accessing-settings">Accessing settings</h2>
|
||||||
|
<p>If you need to access the values of REST framework's API settings in your project,
|
||||||
|
you should use the <code>api_settings</code> object. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.settings import api_settings
|
||||||
|
|
||||||
|
print api_settings.DEFAULT_AUTHENTICATION_CLASSES
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>api_settings</code> object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="api-policy-settings">API policy settings</h2>
|
||||||
|
<p><em>The following settings control the basic API policies, and are applied to every <code>APIView</code> class based view, or <code>@api_view</code> function based view.</em></p>
|
||||||
|
<h4 id="default_renderer_classes">DEFAULT_RENDERER_CLASSES</h4>
|
||||||
|
<p>A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a <code>Response</code> object.</p>
|
||||||
|
<p>Default:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>(
|
||||||
|
'rest_framework.renderers.JSONRenderer',
|
||||||
|
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="default_parser_classes">DEFAULT_PARSER_CLASSES</h4>
|
||||||
|
<p>A list or tuple of parser classes, that determines the default set of parsers used when accessing the <code>request.DATA</code> property.</p>
|
||||||
|
<p>Default:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>(
|
||||||
|
'rest_framework.parsers.JSONParser',
|
||||||
|
'rest_framework.parsers.FormParser',
|
||||||
|
'rest_framework.parsers.MultiPartParser'
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="default_authentication_classes">DEFAULT_AUTHENTICATION_CLASSES</h4>
|
||||||
|
<p>A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the <code>request.user</code> or <code>request.auth</code> properties.</p>
|
||||||
|
<p>Default:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>(
|
||||||
|
'rest_framework.authentication.SessionAuthentication',
|
||||||
|
'rest_framework.authentication.BasicAuthentication'
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="default_permission_classes">DEFAULT_PERMISSION_CLASSES</h4>
|
||||||
|
<p>A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.</p>
|
||||||
|
<p>Default:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>(
|
||||||
|
'rest_framework.permissions.AllowAny',
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="default_throttle_classes">DEFAULT_THROTTLE_CLASSES</h4>
|
||||||
|
<p>A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.</p>
|
||||||
|
<p>Default: <code>()</code></p>
|
||||||
|
<h4 id="default_content_negotiation_class">DEFAULT_CONTENT_NEGOTIATION_CLASS</h4>
|
||||||
|
<p>A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.</p>
|
||||||
|
<p>Default: <code>'rest_framework.negotiation.DefaultContentNegotiation'</code></p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="generic-view-settings">Generic view settings</h2>
|
||||||
|
<p><em>The following settings control the behavior of the generic class based views.</em></p>
|
||||||
|
<h4 id="default_model_serializer_class">DEFAULT_MODEL_SERIALIZER_CLASS</h4>
|
||||||
|
<p>A class that determines the default type of model serializer that should be used by a generic view if <code>model</code> is specified, but <code>serializer_class</code> is not provided.</p>
|
||||||
|
<p>Default: <code>'rest_framework.serializers.ModelSerializer'</code></p>
|
||||||
|
<h4 id="default_pagination_serializer_class">DEFAULT_PAGINATION_SERIALIZER_CLASS</h4>
|
||||||
|
<p>A class the determines the default serialization style for paginated responses.</p>
|
||||||
|
<p>Default: <code>rest_framework.pagination.PaginationSerializer</code></p>
|
||||||
|
<h4 id="default_filter_backends">DEFAULT_FILTER_BACKENDS</h4>
|
||||||
|
<p>A list of filter backend classes that should be used for generic filtering.
|
||||||
|
If set to <code>None</code> then generic filtering is disabled.</p>
|
||||||
|
<h4 id="paginate_by">PAGINATE_BY</h4>
|
||||||
|
<p>The default page size to use for pagination. If set to <code>None</code>, pagination is disabled by default.</p>
|
||||||
|
<p>Default: <code>None</code></p>
|
||||||
|
<h4 id="paginate_by_param">PAGINATE_BY_PARAM</h4>
|
||||||
|
<p>The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to <code>None</code>, clients may not override the default page size.</p>
|
||||||
|
<p>For example, given the following settings:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'PAGINATE_BY': 10,
|
||||||
|
'PAGINATE_BY_PARAM': 'page_size',
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>A client would be able to modify the pagination size by using the <code>page_size</code> query parameter. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>GET http://example.com/api/accounts?page_size=25
|
||||||
|
</code></pre>
|
||||||
|
<p>Default: <code>None</code></p>
|
||||||
|
<h4 id="max_paginate_by">MAX_PAGINATE_BY</h4>
|
||||||
|
<p>The maximum page size to allow when the page size is specified by the client. If set to <code>None</code>, then no maximum limit is applied.</p>
|
||||||
|
<p>For example, given the following settings:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'PAGINATE_BY': 10,
|
||||||
|
'PAGINATE_BY_PARAM': 'page_size',
|
||||||
|
'MAX_PAGINATE_BY': 100
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>A client request like the following would return a paginated list of up to 100 items.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>GET http://example.com/api/accounts?page_size=999
|
||||||
|
</code></pre>
|
||||||
|
<p>Default: <code>None</code></p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="authentication-settings">Authentication settings</h2>
|
||||||
|
<p><em>The following settings control the behavior of unauthenticated requests.</em></p>
|
||||||
|
<h4 id="unauthenticated_user">UNAUTHENTICATED_USER</h4>
|
||||||
|
<p>The class that should be used to initialize <code>request.user</code> for unauthenticated requests.</p>
|
||||||
|
<p>Default: <code>django.contrib.auth.models.AnonymousUser</code></p>
|
||||||
|
<h4 id="unauthenticated_token">UNAUTHENTICATED_TOKEN</h4>
|
||||||
|
<p>The class that should be used to initialize <code>request.auth</code> for unauthenticated requests.</p>
|
||||||
|
<p>Default: <code>None</code></p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="test-settings">Test settings</h2>
|
||||||
|
<p><em>The following settings control the behavior of APIRequestFactory and APIClient</em></p>
|
||||||
|
<h4 id="test_request_default_format">TEST_REQUEST_DEFAULT_FORMAT</h4>
|
||||||
|
<p>The default format that should be used when making test requests.</p>
|
||||||
|
<p>This should match up with the format of one of the renderer classes in the <code>TEST_REQUEST_RENDERER_CLASSES</code> setting.</p>
|
||||||
|
<p>Default: <code>'multipart'</code></p>
|
||||||
|
<h4 id="test_request_renderer_classes">TEST_REQUEST_RENDERER_CLASSES</h4>
|
||||||
|
<p>The renderer classes that are supported when building test requests.</p>
|
||||||
|
<p>The format of any of these renderer classes may be used when constructing a test request, for example: <code>client.post('/users', {'username': 'jamie'}, format='json')</code></p>
|
||||||
|
<p>Default:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>(
|
||||||
|
'rest_framework.renderers.MultiPartRenderer',
|
||||||
|
'rest_framework.renderers.JSONRenderer'
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h2 id="browser-overrides">Browser overrides</h2>
|
||||||
|
<p><em>The following settings provide URL or form-based overrides of the default browser behavior.</em></p>
|
||||||
|
<h4 id="form_method_override">FORM_METHOD_OVERRIDE</h4>
|
||||||
|
<p>The name of a form field that may be used to override the HTTP method of the form.</p>
|
||||||
|
<p>If the value of this setting is <code>None</code> then form method overloading will be disabled.</p>
|
||||||
|
<p>Default: <code>'_method'</code></p>
|
||||||
|
<h4 id="form_content_override">FORM_CONTENT_OVERRIDE</h4>
|
||||||
|
<p>The name of a form field that may be used to override the content of the form payload. Must be used together with <code>FORM_CONTENTTYPE_OVERRIDE</code>.</p>
|
||||||
|
<p>If either setting is <code>None</code> then form content overloading will be disabled.</p>
|
||||||
|
<p>Default: <code>'_content'</code></p>
|
||||||
|
<h4 id="form_contenttype_override">FORM_CONTENTTYPE_OVERRIDE</h4>
|
||||||
|
<p>The name of a form field that may be used to override the content type of the form payload. Must be used together with <code>FORM_CONTENT_OVERRIDE</code>.</p>
|
||||||
|
<p>If either setting is <code>None</code> then form content overloading will be disabled.</p>
|
||||||
|
<p>Default: <code>'_content_type'</code></p>
|
||||||
|
<h4 id="url_accept_override">URL_ACCEPT_OVERRIDE</h4>
|
||||||
|
<p>The name of a URL parameter that may be used to override the HTTP <code>Accept</code> header.</p>
|
||||||
|
<p>If the value of this setting is <code>None</code> then URL accept overloading will be disabled.</p>
|
||||||
|
<p>Default: <code>'accept'</code></p>
|
||||||
|
<h4 id="url_format_override">URL_FORMAT_OVERRIDE</h4>
|
||||||
|
<p>The name of a URL parameter that may be used to override the default <code>Accept</code> header based content negotiation.</p>
|
||||||
|
<p>Default: <code>'format'</code></p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="date-and-time-formatting">Date and time formatting</h2>
|
||||||
|
<p><em>The following settings are used to control how date and time representations may be parsed and rendered.</em></p>
|
||||||
|
<h4 id="datetime_format">DATETIME_FORMAT</h4>
|
||||||
|
<p>A format string that should be used by default for rendering the output of <code>DateTimeField</code> serializer fields. If <code>None</code>, then <code>DateTimeField</code> serializer fields will return Python <code>datetime</code> objects, and the datetime encoding will be determined by the renderer.</p>
|
||||||
|
<p>May be any of <code>None</code>, <code>'iso-8601'</code> or a Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> string.</p>
|
||||||
|
<p>Default: <code>None</code></p>
|
||||||
|
<h4 id="datetime_input_formats">DATETIME_INPUT_FORMATS</h4>
|
||||||
|
<p>A list of format strings that should be used by default for parsing inputs to <code>DateTimeField</code> serializer fields.</p>
|
||||||
|
<p>May be a list including the string <code>'iso-8601'</code> or Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> strings.</p>
|
||||||
|
<p>Default: <code>['iso-8601']</code></p>
|
||||||
|
<h4 id="date_format">DATE_FORMAT</h4>
|
||||||
|
<p>A format string that should be used by default for rendering the output of <code>DateField</code> serializer fields. If <code>None</code>, then <code>DateField</code> serializer fields will return Python <code>date</code> objects, and the date encoding will be determined by the renderer.</p>
|
||||||
|
<p>May be any of <code>None</code>, <code>'iso-8601'</code> or a Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> string.</p>
|
||||||
|
<p>Default: <code>None</code></p>
|
||||||
|
<h4 id="date_input_formats">DATE_INPUT_FORMATS</h4>
|
||||||
|
<p>A list of format strings that should be used by default for parsing inputs to <code>DateField</code> serializer fields.</p>
|
||||||
|
<p>May be a list including the string <code>'iso-8601'</code> or Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> strings.</p>
|
||||||
|
<p>Default: <code>['iso-8601']</code></p>
|
||||||
|
<h4 id="time_format">TIME_FORMAT</h4>
|
||||||
|
<p>A format string that should be used by default for rendering the output of <code>TimeField</code> serializer fields. If <code>None</code>, then <code>TimeField</code> serializer fields will return Python <code>time</code> objects, and the time encoding will be determined by the renderer.</p>
|
||||||
|
<p>May be any of <code>None</code>, <code>'iso-8601'</code> or a Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> string.</p>
|
||||||
|
<p>Default: <code>None</code></p>
|
||||||
|
<h4 id="time_input_formats">TIME_INPUT_FORMATS</h4>
|
||||||
|
<p>A list of format strings that should be used by default for parsing inputs to <code>TimeField</code> serializer fields.</p>
|
||||||
|
<p>May be a list including the string <code>'iso-8601'</code> or Python <a href="http://docs.python.org/2/library/time.html#time.strftime">strftime format</a> strings.</p>
|
||||||
|
<p>Default: <code>['iso-8601']</code></p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="view-names-and-descriptions">View names and descriptions</h2>
|
||||||
|
<p><strong>The following settings are used to generate the view names and descriptions, as used in responses to <code>OPTIONS</code> requests, and as used in the browsable API.</strong></p>
|
||||||
|
<h4 id="view_name_function">VIEW_NAME_FUNCTION</h4>
|
||||||
|
<p>A string representing the function that should be used when generating view names.</p>
|
||||||
|
<p>This should be a function with the following signature:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>view_name(cls, suffix=None)
|
||||||
|
</code></pre>
|
||||||
|
<ul>
|
||||||
|
<li><code>cls</code>: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing <code>cls.__name__</code>.</li>
|
||||||
|
<li><code>suffix</code>: The optional suffix used when differentiating individual views in a viewset.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Default: <code>'rest_framework.views.get_view_name'</code></p>
|
||||||
|
<h4 id="view_description_function">VIEW_DESCRIPTION_FUNCTION</h4>
|
||||||
|
<p>A string representing the function that should be used when generating view descriptions.</p>
|
||||||
|
<p>This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support <code>rst</code> markup in your view docstrings being output in the browsable API.</p>
|
||||||
|
<p>This should be a function with the following signature:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>view_description(cls, html=False)
|
||||||
|
</code></pre>
|
||||||
|
<ul>
|
||||||
|
<li><code>cls</code>: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing <code>cls.__doc__</code></li>
|
||||||
|
<li><code>html</code>: A boolean indicating if HTML output is required. <code>True</code> when used in the browsable API, and <code>False</code> when used in generating <code>OPTIONS</code> responses.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Default: <code>'rest_framework.views.get_view_description'</code></p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="miscellaneous-settings">Miscellaneous settings</h2>
|
||||||
|
<h4 id="exception_handler">EXCEPTION_HANDLER</h4>
|
||||||
|
<p>A string representing the function that should be used when returning a response for any given exception. If the function returns <code>None</code>, a 500 error will be raised.</p>
|
||||||
|
<p>This setting can be changed to support error responses other than the default <code>{"detail": "Failure..."}</code> responses. For example, you can use it to provide API responses like <code>{"errors": [{"message": "Failure...", "code": ""} ...]}</code>.</p>
|
||||||
|
<p>This should be a function with the following signature:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>exception_handler(exc)
|
||||||
|
</code></pre>
|
||||||
|
<ul>
|
||||||
|
<li><code>exc</code>: The exception.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Default: <code>'rest_framework.views.exception_handler'</code></p>
|
||||||
|
<h4 id="format_suffix_kwarg">FORMAT_SUFFIX_KWARG</h4>
|
||||||
|
<p>The name of a parameter in the URL conf that may be used to provide a format suffix.</p>
|
||||||
|
<p>Default: <code>'format'</code></p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
320
api-guide/status-codes.html
Normal file
|
@ -0,0 +1,320 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Status Codes</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Status Codes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="status-codes-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 " href="../api-guide/testing.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/exceptions.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#status-codes">Status Codes</a></li>
|
||||||
|
<li><a href="#informational---1xx">Informational - 1xx</a></li>
|
||||||
|
<li><a href="#successful---2xx">Successful - 2xx</a></li>
|
||||||
|
<li><a href="#redirection---3xx">Redirection - 3xx</a></li>
|
||||||
|
<li><a href="#client-error---4xx">Client Error - 4xx</a></li>
|
||||||
|
<li><a href="#server-error---5xx">Server Error - 5xx</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/status.py"><span class="label label-info">status.py</span></a></p>
|
||||||
|
<h1 id="status-codes">Status Codes</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.</p>
|
||||||
|
<p>— <a href="http://www.ietf.org/rfc/rfc2324.txt">RFC 2324</a>, Hyper Text Coffee Pot Control Protocol</p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import status
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
def empty_view(self):
|
||||||
|
content = {'please move along': 'nothing to see here'}
|
||||||
|
return Response(content, status=status.HTTP_404_NOT_FOUND)
|
||||||
|
</code></pre>
|
||||||
|
<p>The full set of HTTP status codes included in the <code>status</code> module is listed below.</p>
|
||||||
|
<p>For more information on proper usage of HTTP status codes see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">RFC 2616</a>
|
||||||
|
and <a href="http://tools.ietf.org/html/rfc6585">RFC 6585</a>.</p>
|
||||||
|
<h2 id="informational-1xx">Informational - 1xx</h2>
|
||||||
|
<p>This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>HTTP_100_CONTINUE
|
||||||
|
HTTP_101_SWITCHING_PROTOCOLS
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="successful-2xx">Successful - 2xx</h2>
|
||||||
|
<p>This class of status code indicates that the client's request was successfully received, understood, and accepted.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>HTTP_200_OK
|
||||||
|
HTTP_201_CREATED
|
||||||
|
HTTP_202_ACCEPTED
|
||||||
|
HTTP_203_NON_AUTHORITATIVE_INFORMATION
|
||||||
|
HTTP_204_NO_CONTENT
|
||||||
|
HTTP_205_RESET_CONTENT
|
||||||
|
HTTP_206_PARTIAL_CONTENT
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="redirection-3xx">Redirection - 3xx</h2>
|
||||||
|
<p>This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>HTTP_300_MULTIPLE_CHOICES
|
||||||
|
HTTP_301_MOVED_PERMANENTLY
|
||||||
|
HTTP_302_FOUND
|
||||||
|
HTTP_303_SEE_OTHER
|
||||||
|
HTTP_304_NOT_MODIFIED
|
||||||
|
HTTP_305_USE_PROXY
|
||||||
|
HTTP_306_RESERVED
|
||||||
|
HTTP_307_TEMPORARY_REDIRECT
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="client-error-4xx">Client Error - 4xx</h2>
|
||||||
|
<p>The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>HTTP_400_BAD_REQUEST
|
||||||
|
HTTP_401_UNAUTHORIZED
|
||||||
|
HTTP_402_PAYMENT_REQUIRED
|
||||||
|
HTTP_403_FORBIDDEN
|
||||||
|
HTTP_404_NOT_FOUND
|
||||||
|
HTTP_405_METHOD_NOT_ALLOWED
|
||||||
|
HTTP_406_NOT_ACCEPTABLE
|
||||||
|
HTTP_407_PROXY_AUTHENTICATION_REQUIRED
|
||||||
|
HTTP_408_REQUEST_TIMEOUT
|
||||||
|
HTTP_409_CONFLICT
|
||||||
|
HTTP_410_GONE
|
||||||
|
HTTP_411_LENGTH_REQUIRED
|
||||||
|
HTTP_412_PRECONDITION_FAILED
|
||||||
|
HTTP_413_REQUEST_ENTITY_TOO_LARGE
|
||||||
|
HTTP_414_REQUEST_URI_TOO_LONG
|
||||||
|
HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
||||||
|
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
|
||||||
|
HTTP_417_EXPECTATION_FAILED
|
||||||
|
HTTP_428_PRECONDITION_REQUIRED
|
||||||
|
HTTP_429_TOO_MANY_REQUESTS
|
||||||
|
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="server-error-5xx">Server Error - 5xx</h2>
|
||||||
|
<p>Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>HTTP_500_INTERNAL_SERVER_ERROR
|
||||||
|
HTTP_501_NOT_IMPLEMENTED
|
||||||
|
HTTP_502_BAD_GATEWAY
|
||||||
|
HTTP_503_SERVICE_UNAVAILABLE
|
||||||
|
HTTP_504_GATEWAY_TIMEOUT
|
||||||
|
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
|
||||||
|
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
451
api-guide/testing.html
Normal file
|
@ -0,0 +1,451 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Testing</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Testing, APIRequestFactory, APIClient, Test cases, Testing responses, Configuration">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="testing-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 " href="../api-guide/settings.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/status-codes.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#testing">Testing</a></li>
|
||||||
|
<li class="main"><a href="#apirequestfactory">APIRequestFactory</a></li>
|
||||||
|
<li><a href="#creating-test-requests">Creating test requests</a></li>
|
||||||
|
<li><a href="#forcing-authentication">Forcing authentication</a></li>
|
||||||
|
<li><a href="#forcing-csrf-validation">Forcing CSRF validation</a></li>
|
||||||
|
<li class="main"><a href="#apiclient">APIClient</a></li>
|
||||||
|
<li><a href="#making-requests">Making requests</a></li>
|
||||||
|
<li><a href="#authenticating">Authenticating</a></li>
|
||||||
|
<li><a href="#csrf-validation">CSRF validation</a></li>
|
||||||
|
<li class="main"><a href="#test-cases">Test cases</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li class="main"><a href="#testing-responses">Testing responses</a></li>
|
||||||
|
<li><a href="#checking-the-response-data">Checking the response data</a></li>
|
||||||
|
<li><a href="#rendering-responses">Rendering responses</a></li>
|
||||||
|
<li class="main"><a href="#configuration">Configuration</a></li>
|
||||||
|
<li><a href="#setting-the-default-format">Setting the default format</a></li>
|
||||||
|
<li><a href="#setting-the-available-formats">Setting the available formats</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/test.py"><span class="label label-info">test.py</span></a></p>
|
||||||
|
<h1 id="testing">Testing</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Code without tests is broken as designed.</p>
|
||||||
|
<p>— <a href="http://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper">Jacob Kaplan-Moss</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.</p>
|
||||||
|
<h1 id="apirequestfactory">APIRequestFactory</h1>
|
||||||
|
<p>Extends <a href="https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.client.RequestFactory">Django's existing <code>RequestFactory</code> class</a>.</p>
|
||||||
|
<h2 id="creating-test-requests">Creating test requests</h2>
|
||||||
|
<p>The <code>APIRequestFactory</code> class supports an almost identical API to Django's standard <code>RequestFactory</code> class. This means the that standard <code>.get()</code>, <code>.post()</code>, <code>.put()</code>, <code>.patch()</code>, <code>.delete()</code>, <code>.head()</code> and <code>.options()</code> methods are all available.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.test import APIRequestFactory
|
||||||
|
|
||||||
|
# Using the standard RequestFactory API to create a form POST request
|
||||||
|
factory = APIRequestFactory()
|
||||||
|
request = factory.post('/notes/', {'title': 'new idea'})
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="using-the-format-argument">Using the <code>format</code> argument</h4>
|
||||||
|
<p>Methods which create a request body, such as <code>post</code>, <code>put</code> and <code>patch</code>, include a <code>format</code> argument, which make it easy to generate requests using a content type other than multipart form data. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># Create a JSON POST request
|
||||||
|
factory = APIRequestFactory()
|
||||||
|
request = factory.post('/notes/', {'title': 'new idea'}, format='json')
|
||||||
|
</code></pre>
|
||||||
|
<p>By default the available formats are <code>'multipart'</code> and <code>'json'</code>. For compatibility with Django's existing <code>RequestFactory</code> the default format is <code>'multipart'</code>.</p>
|
||||||
|
<p>To support a wider set of request formats, or change the default format, <a href="#configuration">see the configuration section</a>.</p>
|
||||||
|
<h4 id="explicitly-encoding-the-request-body">Explicitly encoding the request body</h4>
|
||||||
|
<p>If you need to explicitly encode the request body, you can do so by setting the <code>content_type</code> flag. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
|
||||||
|
</code></pre>
|
||||||
|
<h4 id="put-and-patch-with-form-data">PUT and PATCH with form data</h4>
|
||||||
|
<p>One difference worth noting between Django's <code>RequestFactory</code> and REST framework's <code>APIRequestFactory</code> is that multipart form data will be encoded for methods other than just <code>.post()</code>.</p>
|
||||||
|
<p>For example, using <code>APIRequestFactory</code>, you can make a form PUT request like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>factory = APIRequestFactory()
|
||||||
|
request = factory.put('/notes/547/', {'title': 'remember to email dave'})
|
||||||
|
</code></pre>
|
||||||
|
<p>Using Django's <code>RequestFactory</code>, you'd need to explicitly encode the data yourself:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.test.client import encode_multipart, RequestFactory
|
||||||
|
|
||||||
|
factory = RequestFactory()
|
||||||
|
data = {'title': 'remember to email dave'}
|
||||||
|
content = encode_multipart('BoUnDaRyStRiNg', data)
|
||||||
|
content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
|
||||||
|
request = factory.put('/notes/547/', content, content_type=content_type)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="forcing-authentication">Forcing authentication</h2>
|
||||||
|
<p>When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.</p>
|
||||||
|
<p>To forcibly authenticate a request, use the <code>force_authenticate()</code> method.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>factory = APIRequestFactory()
|
||||||
|
user = User.objects.get(username='olivia')
|
||||||
|
view = AccountDetail.as_view()
|
||||||
|
|
||||||
|
# Make an authenticated request to the view...
|
||||||
|
request = factory.get('/accounts/django-superstars/')
|
||||||
|
force_authenticate(request, user=user)
|
||||||
|
response = view(request)
|
||||||
|
</code></pre>
|
||||||
|
<p>The signature for the method is <code>force_authenticate(request, user=None, token=None)</code>. When making the call, either or both of the user and token may be set.</p>
|
||||||
|
<p>For example, when forcibly authenticating using a token, you might do something like the following:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>user = User.objects.get(username='olivia')
|
||||||
|
request = factory.get('/accounts/django-superstars/')
|
||||||
|
force_authenticate(request, user=user, token=user.token)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note</strong>: When using <code>APIRequestFactory</code>, the object that is returned is Django's standard <code>HttpRequest</code>, and not REST framework's <code>Request</code> object, which is only generated once the view is called.</p>
|
||||||
|
<p>This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting <code>.token</code> directly will have no effect, and setting <code>.user</code> directly will only work if session authentication is being used.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># Request will only authenticate if `SessionAuthentication` is in use.
|
||||||
|
request = factory.get('/accounts/django-superstars/')
|
||||||
|
request.user = user
|
||||||
|
response = view(request)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h2 id="forcing-csrf-validation">Forcing CSRF validation</h2>
|
||||||
|
<p>By default, requests created with <code>APIRequestFactory</code> will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the <code>enforce_csrf_checks</code> flag when instantiating the factory.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>factory = APIRequestFactory(enforce_csrf_checks=True)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note</strong>: It's worth noting that Django's standard <code>RequestFactory</code> doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="apiclient">APIClient</h1>
|
||||||
|
<p>Extends <a href="https://docs.djangoproject.com/en/dev/topics/testing/overview/#module-django.test.client">Django's existing <code>Client</code> class</a>.</p>
|
||||||
|
<h2 id="making-requests">Making requests</h2>
|
||||||
|
<p>The <code>APIClient</code> class supports the same request interface as <code>APIRequestFactory</code>. This means the that standard <code>.get()</code>, <code>.post()</code>, <code>.put()</code>, <code>.patch()</code>, <code>.delete()</code>, <code>.head()</code> and <code>.options()</code> methods are all available. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
client = APIClient()
|
||||||
|
client.post('/notes/', {'title': 'new idea'}, format='json')
|
||||||
|
</code></pre>
|
||||||
|
<p>To support a wider set of request formats, or change the default format, <a href="#configuration">see the configuration section</a>.</p>
|
||||||
|
<h2 id="authenticating">Authenticating</h2>
|
||||||
|
<h4 id="loginkwargs">.login(**kwargs)</h4>
|
||||||
|
<p>The <code>login</code> method functions exactly as it does with Django's regular <code>Client</code> class. This allows you to authenticate requests against any views which include <code>SessionAuthentication</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># Make all requests in the context of a logged in session.
|
||||||
|
client = APIClient()
|
||||||
|
client.login(username='lauren', password='secret')
|
||||||
|
</code></pre>
|
||||||
|
<p>To logout, call the <code>logout</code> method as usual.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># Log out
|
||||||
|
client.logout()
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>login</code> method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.</p>
|
||||||
|
<h4 id="credentialskwargs">.credentials(**kwargs)</h4>
|
||||||
|
<p>The <code>credentials</code> method can be used to set headers that will then be included on all subsequent requests by the test client.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.authtoken.models import Token
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
# Include an appropriate `Authorization:` header on all requests.
|
||||||
|
token = Token.objects.get(user__username='lauren')
|
||||||
|
client = APIClient()
|
||||||
|
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that calling <code>credentials</code> a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># Stop including any credentials
|
||||||
|
client.credentials()
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>credentials</code> method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.</p>
|
||||||
|
<h4 id="force_authenticateusernone-tokennone">.force_authenticate(user=None, token=None)</h4>
|
||||||
|
<p>Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.</p>
|
||||||
|
<p>This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>user = User.objects.get(username='lauren')
|
||||||
|
client = APIClient()
|
||||||
|
client.force_authenticate(user=user)
|
||||||
|
</code></pre>
|
||||||
|
<p>To unauthenticate subsequent requests, call <code>force_authenticate</code> setting the user and/or token to <code>None</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>client.force_authenticate(user=None)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="csrf-validation">CSRF validation</h2>
|
||||||
|
<p>By default CSRF validation is not applied when using <code>APIClient</code>. If you need to explicitly enable CSRF validation, you can do so by setting the <code>enforce_csrf_checks</code> flag when instantiating the client.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>client = APIClient(enforce_csrf_checks=True)
|
||||||
|
</code></pre>
|
||||||
|
<p>As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling <code>login()</code>.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="test-cases">Test cases</h1>
|
||||||
|
<p>REST framework includes the following test case classes, that mirror the existing Django test case classes, but use <code>APIClient</code> instead of Django's default <code>Client</code>.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>APISimpleTestCase</code></li>
|
||||||
|
<li><code>APITransactionTestCase</code></li>
|
||||||
|
<li><code>APITestCase</code></li>
|
||||||
|
<li><code>APILiveServerTestCase</code></li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>You can use any of REST framework's test case classes as you would for the regular Django test case classes. The <code>self.client</code> attribute will be an <code>APIClient</code> instance.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.core.urlresolvers import reverse
|
||||||
|
from rest_framework import status
|
||||||
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
|
class AccountTests(APITestCase):
|
||||||
|
def test_create_account(self):
|
||||||
|
"""
|
||||||
|
Ensure we can create a new account object.
|
||||||
|
"""
|
||||||
|
url = reverse('account-list')
|
||||||
|
data = {'name': 'DabApps'}
|
||||||
|
response = self.client.post(url, data, format='json')
|
||||||
|
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||||
|
self.assertEqual(response.data, data)
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="testing-responses">Testing responses</h1>
|
||||||
|
<h2 id="checking-the-response-data">Checking the response data</h2>
|
||||||
|
<p>When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.</p>
|
||||||
|
<p>For example, it's easier to inspect <code>request.data</code>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>response = self.client.get('/users/4/')
|
||||||
|
self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
|
||||||
|
</code></pre>
|
||||||
|
<p>Instead of inspecting the result of parsing <code>request.content</code>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>response = self.client.get('/users/4/')
|
||||||
|
self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="rendering-responses">Rendering responses</h2>
|
||||||
|
<p>If you're testing views directly using <code>APIRequestFactory</code>, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access <code>response.content</code>, you'll first need to render the response.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>view = UserDetail.as_view()
|
||||||
|
request = factory.get('/users/4')
|
||||||
|
response = view(request, pk='4')
|
||||||
|
response.render() # Cannot access `response.content` without this.
|
||||||
|
self.assertEqual(response.content, '{"username": "lauren", "id": 4}')
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h1 id="configuration">Configuration</h1>
|
||||||
|
<h2 id="setting-the-default-format">Setting the default format</h2>
|
||||||
|
<p>The default format used to make test requests may be set using the <code>TEST_REQUEST_DEFAULT_FORMAT</code> setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your <code>settings.py</code> file:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
...
|
||||||
|
'TEST_REQUEST_DEFAULT_FORMAT': 'json'
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="setting-the-available-formats">Setting the available formats</h2>
|
||||||
|
<p>If you need to test requests using something other than multipart or json requests, you can do so by setting the <code>TEST_REQUEST_RENDERER_CLASSES</code> setting.</p>
|
||||||
|
<p>For example, to add support for using <code>format='yaml'</code> in test requests, you might have something like this in your <code>settings.py</code> file.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
...
|
||||||
|
'TEST_REQUEST_RENDERER_CLASSES': (
|
||||||
|
'rest_framework.renderers.MultiPartRenderer',
|
||||||
|
'rest_framework.renderers.JSONRenderer',
|
||||||
|
'rest_framework.renderers.YAMLRenderer'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
383
api-guide/throttling.html
Normal file
|
@ -0,0 +1,383 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Throttling</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Throttling, API Reference, Custom throttles">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="throttling-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 " href="../api-guide/filtering.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/permissions.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#throttling">Throttling</a></li>
|
||||||
|
<li><a href="#how-throttling-is-determined">How throttling is determined</a></li>
|
||||||
|
<li><a href="#setting-the-throttling-policy">Setting the throttling policy</a></li>
|
||||||
|
<li><a href="#setting-up-the-cache">Setting up the cache</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#anonratethrottle">AnonRateThrottle</a></li>
|
||||||
|
<li><a href="#userratethrottle">UserRateThrottle</a></li>
|
||||||
|
<li><a href="#scopedratethrottle">ScopedRateThrottle</a></li>
|
||||||
|
<li class="main"><a href="#custom-throttles">Custom throttles</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/throttling.py"><span class="label label-info">throttling.py</span></a></p>
|
||||||
|
<h1 id="throttling">Throttling</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>HTTP/1.1 420 Enhance Your Calm</p>
|
||||||
|
<p><a href="https://dev.twitter.com/docs/error-codes-responses">Twitter API rate limiting response</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Throttling is similar to <a href="permissions.html">permissions</a>, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.</p>
|
||||||
|
<p>As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.</p>
|
||||||
|
<p>Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.</p>
|
||||||
|
<p>Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.</p>
|
||||||
|
<p>Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.</p>
|
||||||
|
<h2 id="how-throttling-is-determined">How throttling is determined</h2>
|
||||||
|
<p>As with permissions and authentication, throttling in REST framework is always defined as a list of classes.</p>
|
||||||
|
<p>Before running the main body of the view each throttle in the list is checked.
|
||||||
|
If any throttle check fails an <code>exceptions.Throttled</code> exception will be raised, and the main body of the view will not run.</p>
|
||||||
|
<h2 id="setting-the-throttling-policy">Setting the throttling policy</h2>
|
||||||
|
<p>The default throttling policy may be set globally, using the <code>DEFAULT_THROTTLE_CLASSES</code> and <code>DEFAULT_THROTTLE_RATES</code> settings. For example.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_THROTTLE_CLASSES': (
|
||||||
|
'rest_framework.throttling.AnonRateThrottle',
|
||||||
|
'rest_framework.throttling.UserRateThrottle'
|
||||||
|
),
|
||||||
|
'DEFAULT_THROTTLE_RATES': {
|
||||||
|
'anon': '100/day',
|
||||||
|
'user': '1000/day'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>The rate descriptions used in <code>DEFAULT_THROTTLE_RATES</code> may include <code>second</code>, <code>minute</code>, <code>hour</code> or <code>day</code> as the throttle period.</p>
|
||||||
|
<p>You can also set the throttling policy on a per-view or per-viewset basis,
|
||||||
|
using the <code>APIView</code> class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.response import Response
|
||||||
|
from rest_framework.throttling import UserRateThrottle
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
class ExampleView(APIView):
|
||||||
|
throttle_classes = (UserRateThrottle,)
|
||||||
|
|
||||||
|
def get(self, request, format=None):
|
||||||
|
content = {
|
||||||
|
'status': 'request was permitted'
|
||||||
|
}
|
||||||
|
return Response(content)
|
||||||
|
</code></pre>
|
||||||
|
<p>Or, if you're using the <code>@api_view</code> decorator with function based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@api_view('GET')
|
||||||
|
@throttle_classes([UserRateThrottle])
|
||||||
|
def example_view(request, format=None):
|
||||||
|
content = {
|
||||||
|
'status': 'request was permitted'
|
||||||
|
}
|
||||||
|
return Response(content)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="setting-up-the-cache">Setting up the cache</h2>
|
||||||
|
<p>The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate <a href="https://docs.djangoproject.com/en/dev/ref/settings/#caches">cache settings</a>. The default value of <code>LocMemCache</code> backend should be okay for simple setups. See Django's <a href="https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache">cache documentation</a> for more details.</p>
|
||||||
|
<p>If you need to use a cache other than <code>'default'</code>, you can do so by creating a custom throttle class and setting the <code>cache</code> attribute. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CustomAnonRateThrottle(AnonRateThrottle):
|
||||||
|
cache = get_cache('alternate')
|
||||||
|
</code></pre>
|
||||||
|
<p>You'll need to rememeber to also set your custom throttle class in the <code>'DEFAULT_THROTTLE_CLASSES'</code> settings key, or using the <code>throttle_classes</code> view attribute.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="anonratethrottle">AnonRateThrottle</h2>
|
||||||
|
<p>The <code>AnonRateThrottle</code> will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.</p>
|
||||||
|
<p>The allowed request rate is determined from one of the following (in order of preference).</p>
|
||||||
|
<ul>
|
||||||
|
<li>The <code>rate</code> property on the class, which may be provided by overriding <code>AnonRateThrottle</code> and setting the property.</li>
|
||||||
|
<li>The <code>DEFAULT_THROTTLE_RATES['anon']</code> setting.</li>
|
||||||
|
</ul>
|
||||||
|
<p><code>AnonRateThrottle</code> is suitable if you want to restrict the rate of requests from unknown sources.</p>
|
||||||
|
<h2 id="userratethrottle">UserRateThrottle</h2>
|
||||||
|
<p>The <code>UserRateThrottle</code> will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.</p>
|
||||||
|
<p>The allowed request rate is determined from one of the following (in order of preference).</p>
|
||||||
|
<ul>
|
||||||
|
<li>The <code>rate</code> property on the class, which may be provided by overriding <code>UserRateThrottle</code> and setting the property.</li>
|
||||||
|
<li>The <code>DEFAULT_THROTTLE_RATES['user']</code> setting.</li>
|
||||||
|
</ul>
|
||||||
|
<p>An API may have multiple <code>UserRateThrottles</code> in place at the same time. To do so, override <code>UserRateThrottle</code> and set a unique "scope" for each class.</p>
|
||||||
|
<p>For example, multiple user throttle rates could be implemented by using the following classes...</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class BurstRateThrottle(UserRateThrottle):
|
||||||
|
scope = 'burst'
|
||||||
|
|
||||||
|
class SustainedRateThrottle(UserRateThrottle):
|
||||||
|
scope = 'sustained'
|
||||||
|
</code></pre>
|
||||||
|
<p>...and the following settings.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_THROTTLE_CLASSES': (
|
||||||
|
'example.throttles.BurstRateThrottle',
|
||||||
|
'example.throttles.SustainedRateThrottle'
|
||||||
|
),
|
||||||
|
'DEFAULT_THROTTLE_RATES': {
|
||||||
|
'burst': '60/min',
|
||||||
|
'sustained': '1000/day'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p><code>UserRateThrottle</code> is suitable if you want simple global rate restrictions per-user.</p>
|
||||||
|
<h2 id="scopedratethrottle">ScopedRateThrottle</h2>
|
||||||
|
<p>The <code>ScopedRateThrottle</code> class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a <code>.throttle_scope</code> property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.</p>
|
||||||
|
<p>The allowed request rate is determined by the <code>DEFAULT_THROTTLE_RATES</code> setting using a key from the request "scope".</p>
|
||||||
|
<p>For example, given the following views...</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class ContactListView(APIView):
|
||||||
|
throttle_scope = 'contacts'
|
||||||
|
...
|
||||||
|
|
||||||
|
class ContactDetailView(ApiView):
|
||||||
|
throttle_scope = 'contacts'
|
||||||
|
...
|
||||||
|
|
||||||
|
class UploadView(APIView):
|
||||||
|
throttle_scope = 'uploads'
|
||||||
|
...
|
||||||
|
</code></pre>
|
||||||
|
<p>...and the following settings.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_THROTTLE_CLASSES': (
|
||||||
|
'rest_framework.throttling.ScopedRateThrottle'
|
||||||
|
),
|
||||||
|
'DEFAULT_THROTTLE_RATES': {
|
||||||
|
'contacts': '1000/day',
|
||||||
|
'uploads': '20/day'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>User requests to either <code>ContactListView</code> or <code>ContactDetailView</code> would be restricted to a total of 1000 requests per-day. User requests to <code>UploadView</code> would be restricted to 20 requests per day.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="custom-throttles">Custom throttles</h1>
|
||||||
|
<p>To create a custom throttle, override <code>BaseThrottle</code> and implement <code>.allow_request(self, request, view)</code>. The method should return <code>True</code> if the request should be allowed, and <code>False</code> otherwise.</p>
|
||||||
|
<p>Optionally you may also override the <code>.wait()</code> method. If implemented, <code>.wait()</code> should return a recommended number of seconds to wait before attempting the next request, or <code>None</code>. The <code>.wait()</code> method will only be called if <code>.allow_request()</code> has previously returned <code>False</code>.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class RandomRateThrottle(throttles.BaseThrottle):
|
||||||
|
def allow_request(self, request, view):
|
||||||
|
return random.randint(1, 10) == 1
|
||||||
|
</code></pre>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
360
api-guide/views.html
Normal file
|
@ -0,0 +1,360 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Class Based Views</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Class Based Views, Function Based Views">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="views-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 " href="../api-guide/generic-views.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/responses.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#class-based-views">Class Based Views</a></li>
|
||||||
|
<li><a href="#api-policy-attributes">API policy attributes</a></li>
|
||||||
|
<li><a href="#api-policy-instantiation-methods">API policy instantiation methods</a></li>
|
||||||
|
<li><a href="#api-policy-implementation-methods">API policy implementation methods</a></li>
|
||||||
|
<li><a href="#dispatch-methods">Dispatch methods</a></li>
|
||||||
|
<li class="main"><a href="#function-based-views">Function Based Views</a></li>
|
||||||
|
<li><a href="#@api_view()">@api_view()</a></li>
|
||||||
|
<li><a href="#api-policy-decorators">API policy decorators</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/decorators.py"><span class="label label-info">decorators.py</span></a> <a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/views.py"><span class="label label-info">views.py</span></a></p>
|
||||||
|
<h1 id="class-based-views">Class Based Views</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Django's class based views are a welcome departure from the old-style views.</p>
|
||||||
|
<p>— <a href="http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html">Reinout van Rees</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>REST framework provides an <code>APIView</code> class, which subclasses Django's <code>View</code> class.</p>
|
||||||
|
<p><code>APIView</code> classes are different from regular <code>View</code> classes in the following ways:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Requests passed to the handler methods will be REST framework's <code>Request</code> instances, not Django's <code>HttpRequest</code> instances.</li>
|
||||||
|
<li>Handler methods may return REST framework's <code>Response</code>, instead of Django's <code>HttpResponse</code>. The view will manage content negotiation and setting the correct renderer on the response.</li>
|
||||||
|
<li>Any <code>APIException</code> exceptions will be caught and mediated into appropriate responses.</li>
|
||||||
|
<li>Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Using the <code>APIView</code> class is pretty much the same as using a regular <code>View</code> class, as usual, the incoming request is dispatched to an appropriate handler method such as <code>.get()</code> or <code>.post()</code>. Additionally, a number of attributes may be set on the class that control various aspects of the API policy.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.views import APIView
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework import authentication, permissions
|
||||||
|
|
||||||
|
class ListUsers(APIView):
|
||||||
|
"""
|
||||||
|
View to list all users in the system.
|
||||||
|
|
||||||
|
* Requires token authentication.
|
||||||
|
* Only admin users are able to access this view.
|
||||||
|
"""
|
||||||
|
authentication_classes = (authentication.TokenAuthentication,)
|
||||||
|
permission_classes = (permissions.IsAdminUser,)
|
||||||
|
|
||||||
|
def get(self, request, format=None):
|
||||||
|
"""
|
||||||
|
Return a list of all users.
|
||||||
|
"""
|
||||||
|
usernames = [user.username for user in User.objects.all()]
|
||||||
|
return Response(usernames)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="api-policy-attributes">API policy attributes</h2>
|
||||||
|
<p>The following attributes control the pluggable aspects of API views.</p>
|
||||||
|
<h3 id="renderer_classes">.renderer_classes</h3>
|
||||||
|
<h3 id="parser_classes">.parser_classes</h3>
|
||||||
|
<h3 id="authentication_classes">.authentication_classes</h3>
|
||||||
|
<h3 id="throttle_classes">.throttle_classes</h3>
|
||||||
|
<h3 id="permission_classes">.permission_classes</h3>
|
||||||
|
<h3 id="content_negotiation_class">.content_negotiation_class</h3>
|
||||||
|
<h2 id="api-policy-instantiation-methods">API policy instantiation methods</h2>
|
||||||
|
<p>The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.</p>
|
||||||
|
<h3 id="get_renderersself">.get_renderers(self)</h3>
|
||||||
|
<h3 id="get_parsersself">.get_parsers(self)</h3>
|
||||||
|
<h3 id="get_authenticatorsself">.get_authenticators(self)</h3>
|
||||||
|
<h3 id="get_throttlesself">.get_throttles(self)</h3>
|
||||||
|
<h3 id="get_permissionsself">.get_permissions(self)</h3>
|
||||||
|
<h3 id="get_content_negotiatorself">.get_content_negotiator(self)</h3>
|
||||||
|
<h2 id="api-policy-implementation-methods">API policy implementation methods</h2>
|
||||||
|
<p>The following methods are called before dispatching to the handler method.</p>
|
||||||
|
<h3 id="check_permissionsself-request">.check_permissions(self, request)</h3>
|
||||||
|
<h3 id="check_throttlesself-request">.check_throttles(self, request)</h3>
|
||||||
|
<h3 id="perform_content_negotiationself-request-forcefalse">.perform_content_negotiation(self, request, force=False)</h3>
|
||||||
|
<h2 id="dispatch-methods">Dispatch methods</h2>
|
||||||
|
<p>The following methods are called directly by the view's <code>.dispatch()</code> method.
|
||||||
|
These perform any actions that need to occur before or after calling the handler methods such as <code>.get()</code>, <code>.post()</code>, <code>put()</code>, <code>patch()</code> and <code>.delete()</code>.</p>
|
||||||
|
<h3 id="initialself-request-42args-kwargs">.initial(self, request, *args, **kwargs)</h3>
|
||||||
|
<p>Performs any actions that need to occur before the handler method gets called.
|
||||||
|
This method is used to enforce permissions and throttling, and perform content negotiation.</p>
|
||||||
|
<p>You won't typically need to override this method.</p>
|
||||||
|
<h3 id="handle_exceptionself-exc">.handle_exception(self, exc)</h3>
|
||||||
|
<p>Any exception thrown by the handler method will be passed to this method, which either returns a <code>Response</code> instance, or re-raises the exception.</p>
|
||||||
|
<p>The default implementation handles any subclass of <code>rest_framework.exceptions.APIException</code>, as well as Django's <code>Http404</code> and <code>PermissionDenied</code> exceptions, and returns an appropriate error response.</p>
|
||||||
|
<p>If you need to customize the error responses your API returns you should subclass this method.</p>
|
||||||
|
<h3 id="initialize_requestself-request-42args-kwargs">.initialize_request(self, request, *args, **kwargs)</h3>
|
||||||
|
<p>Ensures that the request object that is passed to the handler method is an instance of <code>Request</code>, rather than the usual Django <code>HttpRequest</code>.</p>
|
||||||
|
<p>You won't typically need to override this method.</p>
|
||||||
|
<h3 id="finalize_responseself-request-response-42args-kwargs">.finalize_response(self, request, response, *args, **kwargs)</h3>
|
||||||
|
<p>Ensures that any <code>Response</code> object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.</p>
|
||||||
|
<p>You won't typically need to override this method.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="function-based-views">Function Based Views</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Saying [that Class based views] is always the superior solution is a mistake.</p>
|
||||||
|
<p>— <a href="http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html">Nick Coghlan</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of <code>Request</code> (rather than the usual Django <code>HttpRequest</code>) and allows them to return a <code>Response</code> (instead of a Django <code>HttpResponse</code>), and allow you to configure how the request is processed.</p>
|
||||||
|
<h2 id="api_view">@api_view()</h2>
|
||||||
|
<p><strong>Signature:</strong> <code>@api_view(http_method_names)</code></p>
|
||||||
|
<p>The core of this functionality is the <code>api_view</code> decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.decorators import api_view
|
||||||
|
|
||||||
|
@api_view(['GET'])
|
||||||
|
def hello_world(request):
|
||||||
|
return Response({"message": "Hello, world!"})
|
||||||
|
</code></pre>
|
||||||
|
<p>This view will use the default renderers, parsers, authentication classes etc specified in the <a href="api-guide/settings.html">settings</a>.</p>
|
||||||
|
<h2 id="api-policy-decorators">API policy decorators</h2>
|
||||||
|
<p>To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come <em>after</em> (below) the <code>@api_view</code> decorator. For example, to create a view that uses a <a href="api-guide/throttling.html">throttle</a> to ensure it can only be called once per day by a particular user, use the <code>@throttle_classes</code> decorator, passing a list of throttle classes:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.decorators import api_view, throttle_classes
|
||||||
|
from rest_framework.throttling import UserRateThrottle
|
||||||
|
|
||||||
|
class OncePerDayUserThrottle(UserRateThrottle):
|
||||||
|
rate = '1/day'
|
||||||
|
|
||||||
|
@api_view(['GET'])
|
||||||
|
@throttle_classes([OncePerDayUserThrottle])
|
||||||
|
def view(request):
|
||||||
|
return Response({"message": "Hello for today! See you tomorrow!"})
|
||||||
|
</code></pre>
|
||||||
|
<p>These decorators correspond to the attributes set on <code>APIView</code> subclasses, described above.</p>
|
||||||
|
<p>The available decorators are:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>@renderer_classes(...)</code></li>
|
||||||
|
<li><code>@parser_classes(...)</code></li>
|
||||||
|
<li><code>@authentication_classes(...)</code></li>
|
||||||
|
<li><code>@throttle_classes(...)</code></li>
|
||||||
|
<li><code>@permission_classes(...)</code></li>
|
||||||
|
</ul>
|
||||||
|
<p>Each of these decorators takes a single argument which must be a list or tuple of classes.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
437
api-guide/viewsets.html
Normal file
|
@ -0,0 +1,437 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - ViewSets</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, ViewSets, API Reference, Custom ViewSet base classes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="viewsets-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 " href="../api-guide/routers.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/generic-views.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#viewsets">ViewSets</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li><a href="#marking-extra-methods-for-routing">Marking extra methods for routing</a></li>
|
||||||
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||||||
|
<li><a href="#viewset">ViewSet</a></li>
|
||||||
|
<li><a href="#genericviewset">GenericViewSet</a></li>
|
||||||
|
<li><a href="#modelviewset">ModelViewSet</a></li>
|
||||||
|
<li><a href="#readonlymodelviewset">ReadOnlyModelViewSet</a></li>
|
||||||
|
<li class="main"><a href="#custom-viewset-base-classes">Custom ViewSet base classes</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/viewsets.py"><span class="label label-info">viewsets.py</span></a></p>
|
||||||
|
<h1 id="viewsets">ViewSets</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.</p>
|
||||||
|
<p>— <a href="http://guides.rubyonrails.org/routing.html">Ruby on Rails Documentation</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>Django REST framework allows you to combine the logic for a set of related views in a single class, called a <code>ViewSet</code>. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.</p>
|
||||||
|
<p>A <code>ViewSet</code> class is simply <strong>a type of class-based View, that does not provide any method handlers</strong> such as <code>.get()</code> or <code>.post()</code>, and instead provides actions such as <code>.list()</code> and <code>.create()</code>.</p>
|
||||||
|
<p>The method handlers for a <code>ViewSet</code> are only bound to the corresponding actions at the point of finalizing the view, using the <code>.as_view()</code> method.</p>
|
||||||
|
<p>Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>Let's define a simple viewset that can be used to list or retrieve all the users in the system.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from django.shortcuts import get_object_or_404
|
||||||
|
from myapps.serializers import UserSerializer
|
||||||
|
from rest_framework import viewsets
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
class UserViewSet(viewsets.ViewSet):
|
||||||
|
"""
|
||||||
|
A simple ViewSet that for listing or retrieving users.
|
||||||
|
"""
|
||||||
|
def list(self, request):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer = UserSerializer(queryset, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
def retrieve(self, request, pk=None):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
user = get_object_or_404(queryset, pk=pk)
|
||||||
|
serializer = UserSerializer(user)
|
||||||
|
return Response(serializer.data)
|
||||||
|
</code></pre>
|
||||||
|
<p>If we need to, we can bind this viewset into two separate views, like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>user_list = UserViewSet.as_view({'get': 'list'})
|
||||||
|
user_detail = UserViewSet.as_view({'get': 'retrieve'})
|
||||||
|
</code></pre>
|
||||||
|
<p>Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from myapp.views import UserViewSet
|
||||||
|
from rest_framework.routers import DefaultRouter
|
||||||
|
|
||||||
|
router = DefaultRouter()
|
||||||
|
router.register(r'users', UserViewSet)
|
||||||
|
urlpatterns = router.urls
|
||||||
|
</code></pre>
|
||||||
|
<p>Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
A viewset for viewing and editing user instances.
|
||||||
|
"""
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
queryset = User.objects.all()
|
||||||
|
</code></pre>
|
||||||
|
<p>There are two main advantages of using a <code>ViewSet</code> class over using a <code>View</code> class.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Repeated logic can be combined into a single class. In the above example, we only need to specify the <code>queryset</code> once, and it'll be used across multiple views.</li>
|
||||||
|
<li>By using routers, we no longer need to deal with wiring up the URL conf ourselves.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.</p>
|
||||||
|
<h2 id="marking-extra-methods-for-routing">Marking extra methods for routing</h2>
|
||||||
|
<p>The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserViewSet(viewsets.ViewSet):
|
||||||
|
"""
|
||||||
|
Example empty viewset demonstrating the standard
|
||||||
|
actions that will be handled by a router class.
|
||||||
|
|
||||||
|
If you're using format suffixes, make sure to also include
|
||||||
|
the `format=None` keyword argument for each action.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def list(self, request):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def create(self, request):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def retrieve(self, request, pk=None):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def update(self, request, pk=None):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def partial_update(self, request, pk=None):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def destroy(self, request, pk=None):
|
||||||
|
pass
|
||||||
|
</code></pre>
|
||||||
|
<p>If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the <code>@link</code> or <code>@action</code> decorators. The <code>@link</code> decorator will route <code>GET</code> requests, and the <code>@action</code> decorator will route <code>POST</code> requests.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
from rest_framework import viewsets
|
||||||
|
from rest_framework import status
|
||||||
|
from rest_framework.decorators import action
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from myapp.serializers import UserSerializer, PasswordSerializer
|
||||||
|
|
||||||
|
class UserViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
A viewset that provides the standard actions
|
||||||
|
"""
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
|
||||||
|
@action()
|
||||||
|
def set_password(self, request, pk=None):
|
||||||
|
user = self.get_object()
|
||||||
|
serializer = PasswordSerializer(data=request.DATA)
|
||||||
|
if serializer.is_valid():
|
||||||
|
user.set_password(serializer.data['password'])
|
||||||
|
user.save()
|
||||||
|
return Response({'status': 'password set'})
|
||||||
|
else:
|
||||||
|
return Response(serializer.errors,
|
||||||
|
status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>@action</code> and <code>@link</code> decorators can additionally take extra arguments that will be set for the routed view only. For example...</p>
|
||||||
|
<pre class="prettyprint lang-py"><code> @action(permission_classes=[IsAdminOrIsSelf])
|
||||||
|
def set_password(self, request, pk=None):
|
||||||
|
...
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>@action</code> decorator will route <code>POST</code> requests by default, but may also accept other HTTP methods, by using the <code>method</code> argument. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code> @action(methods=['POST', 'DELETE'])
|
||||||
|
def unset_password(self, request, pk=None):
|
||||||
|
...
|
||||||
|
</code></pre>
|
||||||
|
<p>The two new actions will then be available at the urls <code>^users/{pk}/set_password/$</code> and <code>^users/{pk}/unset_password/$</code></p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-reference">API Reference</h1>
|
||||||
|
<h2 id="viewset">ViewSet</h2>
|
||||||
|
<p>The <code>ViewSet</code> class inherits from <code>APIView</code>. You can use any of the standard attributes such as <code>permission_classes</code>, <code>authentication_classes</code> in order to control the API policy on the viewset.</p>
|
||||||
|
<p>The <code>ViewSet</code> class does not provide any implementations of actions. In order to use a <code>ViewSet</code> class you'll override the class and define the action implementations explicitly.</p>
|
||||||
|
<h2 id="genericviewset">GenericViewSet</h2>
|
||||||
|
<p>The <code>GenericViewSet</code> class inherits from <code>GenericAPIView</code>, and provides the default set of <code>get_object</code>, <code>get_queryset</code> methods and other generic view base behavior, but does not include any actions by default.</p>
|
||||||
|
<p>In order to use a <code>GenericViewSet</code> class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.</p>
|
||||||
|
<h2 id="modelviewset">ModelViewSet</h2>
|
||||||
|
<p>The <code>ModelViewSet</code> class inherits from <code>GenericAPIView</code> and includes implementations for various actions, by mixing in the behavior of the various mixin classes.</p>
|
||||||
|
<p>The actions provided by the <code>ModelViewSet</code> class are <code>.list()</code>, <code>.retrieve()</code>, <code>.create()</code>, <code>.update()</code>, and <code>.destroy()</code>.</p>
|
||||||
|
<h4 id="example_1">Example</h4>
|
||||||
|
<p>Because <code>ModelViewSet</code> extends <code>GenericAPIView</code>, you'll normally need to provide at least the <code>queryset</code> and <code>serializer_class</code> attributes. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
A simple ViewSet for viewing and editing accounts.
|
||||||
|
"""
|
||||||
|
queryset = Account.objects.all()
|
||||||
|
serializer_class = AccountSerializer
|
||||||
|
permission_classes = [IsAccountAdminOrReadOnly]
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that you can use any of the standard attributes or method overrides provided by <code>GenericAPIView</code>. For example, to use a <code>ViewSet</code> that dynamically determines the queryset it should operate on, you might do something like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
A simple ViewSet for viewing and editing the accounts
|
||||||
|
associated with the user.
|
||||||
|
"""
|
||||||
|
serializer_class = AccountSerializer
|
||||||
|
permission_classes = [IsAccountAdminOrReadOnly]
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
return self.request.user.accounts.all()
|
||||||
|
</code></pre>
|
||||||
|
<p>Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.</p>
|
||||||
|
<h2 id="readonlymodelviewset">ReadOnlyModelViewSet</h2>
|
||||||
|
<p>The <code>ReadOnlyModelViewSet</code> class also inherits from <code>GenericAPIView</code>. As with <code>ModelViewSet</code> it also includes implementations for various actions, but unlike <code>ModelViewSet</code> only provides the 'read-only' actions, <code>.list()</code> and <code>.retrieve()</code>.</p>
|
||||||
|
<h4 id="example_2">Example</h4>
|
||||||
|
<p>As with <code>ModelViewSet</code>, you'll normally need to provide at least the <code>queryset</code> and <code>serializer_class</code> attributes. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountViewSet(viewsets.ReadOnlyModelViewSet):
|
||||||
|
"""
|
||||||
|
A simple ViewSet for viewing accounts.
|
||||||
|
"""
|
||||||
|
queryset = Account.objects.all()
|
||||||
|
serializer_class = AccountSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>Again, as with <code>ModelViewSet</code>, you can use any of the standard attributes and method overrides available to <code>GenericAPIView</code>.</p>
|
||||||
|
<h1 id="custom-viewset-base-classes">Custom ViewSet base classes</h1>
|
||||||
|
<p>You may need to provide custom <code>ViewSet</code> classes that do not have the full set of <code>ModelViewSet</code> actions, or that customize the behavior in some other way.</p>
|
||||||
|
<h2 id="example_3">Example</h2>
|
||||||
|
<p>To create a base viewset class that provides <code>create</code>, <code>list</code> and <code>retrieve</code> operations, inherit from <code>GenericViewSet</code>, and mixin the required actions:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class CreateListRetrieveViewSet(mixins.CreateModelMixin,
|
||||||
|
mixins.ListModelMixin,
|
||||||
|
mixins.RetrieveModelMixin,
|
||||||
|
viewsets.GenericViewSet):
|
||||||
|
"""
|
||||||
|
A viewset that provides `retrieve`, `update`, and `list` actions.
|
||||||
|
|
||||||
|
To use it, override the class and set the `.queryset` and
|
||||||
|
`.serializer_class` attributes.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
</code></pre>
|
||||||
|
<p>By creating your own base <code>ViewSet</code> classes, you can provide common behavior that can be reused in multiple viewsets across your API.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
1058
css/bootstrap-responsive.css
vendored
Executable file
5774
css/bootstrap.css
vendored
Executable file
309
css/default.css
Normal file
|
@ -0,0 +1,309 @@
|
||||||
|
/* Set the body padding-top when above 980px to push the content down from
|
||||||
|
below the navbar, which is fixed at >980px screen widths. */
|
||||||
|
pre {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dropdown .dropdown-menu {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dropdown.open .dropdown-menu {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.repo-link {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Header link to GitHub */
|
||||||
|
.repo-link {
|
||||||
|
float: right;
|
||||||
|
margin-right: 10px;
|
||||||
|
margin-top: 9px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.index-page #main-content p.badges {
|
||||||
|
padding-bottom: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* GitHub 'Star' badge */
|
||||||
|
body.index-page #main-content iframe.github-star-button {
|
||||||
|
float: right;
|
||||||
|
margin-top: -12px;
|
||||||
|
margin-right: -15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tweet button */
|
||||||
|
body.index-page #main-content iframe.twitter-share-button {
|
||||||
|
float: right;
|
||||||
|
margin-top: -12px;
|
||||||
|
margin-right: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Travis CI badge */
|
||||||
|
body.index-page #main-content img.travis-build-image {
|
||||||
|
float: right;
|
||||||
|
margin-right: 8px;
|
||||||
|
margin-top: -11px;
|
||||||
|
margin-bottom: 0px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Github source file badges */
|
||||||
|
a.github {
|
||||||
|
float: right;
|
||||||
|
margin-top: -12px;
|
||||||
|
margin-right: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.github:hover {
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* */
|
||||||
|
body hr {
|
||||||
|
border-top: 1px dotted #A30000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Force TOC text to not overrun */
|
||||||
|
#table-of-contents {
|
||||||
|
overflow: hidden;
|
||||||
|
margin: 0 0 20px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Code blocks should scroll horizontally */
|
||||||
|
pre {
|
||||||
|
overflow: auto;
|
||||||
|
word-wrap: normal;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Preserve the spacing of the navbar across different screen sizes. */
|
||||||
|
.navbar-inner {
|
||||||
|
/*padding: 5px 0;*/
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 979px) {
|
||||||
|
.navbar .brand {
|
||||||
|
margin-left: 0;
|
||||||
|
padding-left: 0;
|
||||||
|
}
|
||||||
|
.navbar-inner .container-fluid {
|
||||||
|
padding-left: 15px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-list li.main {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-list a {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-list > li > a {
|
||||||
|
padding: 2px 15px 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Set the table of contents to static so it flows back into the content when
|
||||||
|
viewed on tablets and smaller. */
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
#table-of-contents {
|
||||||
|
position: static;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* When the page is in two-column layout, give the main content some room
|
||||||
|
to breath on the left. */
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
#main-content {
|
||||||
|
padding-left: 1em;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cutesy quote styling */
|
||||||
|
blockquote {
|
||||||
|
font-family: Georgia, serif;
|
||||||
|
font-size: 18px;
|
||||||
|
font-style: italic;
|
||||||
|
margin: 0.25em 0;
|
||||||
|
padding: 0.25em 40px;
|
||||||
|
line-height: 1.45;
|
||||||
|
position: relative;
|
||||||
|
color: #383838;
|
||||||
|
border-left: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
blockquote:before {
|
||||||
|
display: block;
|
||||||
|
content: "\201C";
|
||||||
|
font-size: 80px;
|
||||||
|
position: absolute;
|
||||||
|
left: -10px;
|
||||||
|
top: -20px;
|
||||||
|
color: #7a7a7a;
|
||||||
|
}
|
||||||
|
|
||||||
|
blockquote p:last-child {
|
||||||
|
color: #999999;
|
||||||
|
font-size: 14px;
|
||||||
|
display: block;
|
||||||
|
margin-top: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*=== dabapps bootstrap styles ====*/
|
||||||
|
|
||||||
|
html{
|
||||||
|
width:100%;
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
body, .navbar .navbar-inner .container-fluid{
|
||||||
|
max-width: 1150px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
body{
|
||||||
|
background: url("../img/grid.png") repeat-x;
|
||||||
|
background-attachment: fixed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* custom navigation styles */
|
||||||
|
|
||||||
|
.navbar .navbar-inner{
|
||||||
|
background: #2C2C2C;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-top: 5px solid #A30000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-list > .active > a, .navbar .navbar-inner .nav li a:hover {
|
||||||
|
background:#212121;
|
||||||
|
color:white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{
|
||||||
|
color: #A30000;
|
||||||
|
}
|
||||||
|
.navbar .navbar-inner .dropdown-menu li a:hover{
|
||||||
|
background: #eeeeee;
|
||||||
|
color: #c20000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* custom general page styles */
|
||||||
|
.hero-unit h2, .hero-unit h1{
|
||||||
|
color: #A30000;
|
||||||
|
}
|
||||||
|
|
||||||
|
body a{
|
||||||
|
color: #A30000;
|
||||||
|
}
|
||||||
|
|
||||||
|
body a:hover{
|
||||||
|
color: #c20000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* subnavigation styles */
|
||||||
|
|
||||||
|
@media (min-width: 767px) {
|
||||||
|
.sidebar-nav-fixed {
|
||||||
|
position:fixed;
|
||||||
|
width:19%;
|
||||||
|
max-width: 240px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar {
|
||||||
|
position: fixed;
|
||||||
|
}
|
||||||
|
.navbar .navbar-inner .container-fluid{
|
||||||
|
max-width: 1110px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* sticky footer and footer */
|
||||||
|
html, body {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
.wrapper {
|
||||||
|
min-height: 100%;
|
||||||
|
height: auto !important;
|
||||||
|
height: 100%;
|
||||||
|
margin: 0 auto -60px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.body-content{
|
||||||
|
padding-top: 70px;
|
||||||
|
padding-bottom: 70px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 979px) {
|
||||||
|
.navbar-fixed-top .navbar-inner {
|
||||||
|
padding: 0px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
.body-content{
|
||||||
|
padding-top: 0px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
footer.span12 {
|
||||||
|
width: 95%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
footer, .push {
|
||||||
|
height: 60px; /* .push must be the same height as .footer */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
footer p {
|
||||||
|
text-align: center;
|
||||||
|
color: gray;
|
||||||
|
border-top: 1px solid #DDD;
|
||||||
|
padding-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
footer a {
|
||||||
|
color: gray;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
footer a:hover {
|
||||||
|
color: gray;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-inverse {
|
||||||
|
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#606060), to(#404040)) !important;
|
||||||
|
background-image: -webkit-linear-gradient(top, #606060, #404040) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-open .modal,.btn:focus{outline:none;}
|
||||||
|
|
||||||
|
@media (max-width: 650px) {
|
||||||
|
.repo-link.btn-inverse {display: none;}
|
||||||
|
}
|
||||||
|
|
||||||
|
td, th {
|
||||||
|
padding: 0.25em;
|
||||||
|
background-color: #f7f7f9;
|
||||||
|
border-color: #e1e1e8;
|
||||||
|
}
|
||||||
|
|
||||||
|
table {
|
||||||
|
border-color: white;
|
||||||
|
margin-bottom: 0.6em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.side-nav {
|
||||||
|
overflow-y: scroll;
|
||||||
|
}
|
30
css/prettify.css
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
.com { color: #93a1a1; }
|
||||||
|
.lit { color: #195f91; }
|
||||||
|
.pun, .opn, .clo { color: #93a1a1; }
|
||||||
|
.fun { color: #dc322f; }
|
||||||
|
.str, .atv { color: #D14; }
|
||||||
|
.kwd, .prettyprint .tag { color: #1e347b; }
|
||||||
|
.typ, .atn, .dec, .var { color: teal; }
|
||||||
|
.pln { color: #48484c; }
|
||||||
|
|
||||||
|
.prettyprint {
|
||||||
|
padding: 8px;
|
||||||
|
background-color: #f7f7f9;
|
||||||
|
border: 1px solid #e1e1e8;
|
||||||
|
}
|
||||||
|
.prettyprint.linenums {
|
||||||
|
-webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
|
||||||
|
-moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
|
||||||
|
box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Specify class=linenums on a pre to get line numbering */
|
||||||
|
ol.linenums {
|
||||||
|
margin: 0 0 0 33px; /* IE indents via margin-left */
|
||||||
|
}
|
||||||
|
ol.linenums li {
|
||||||
|
padding-left: 12px;
|
||||||
|
color: #bebec5;
|
||||||
|
line-height: 20px;
|
||||||
|
text-shadow: 0 1px 0 #fff;
|
||||||
|
}
|
BIN
img/apiary.png
Normal file
After Width: | Height: | Size: 54 KiB |
BIN
img/autocomplete.png
Normal file
After Width: | Height: | Size: 57 KiB |
BIN
img/cerulean.png
Normal file
After Width: | Height: | Size: 61 KiB |
BIN
img/django-rest-swagger.png
Normal file
After Width: | Height: | Size: 75 KiB |
BIN
img/favicon.ico
Normal file
After Width: | Height: | Size: 2.2 KiB |
BIN
img/glyphicons-halflings-white.png
Normal file
After Width: | Height: | Size: 8.6 KiB |
BIN
img/glyphicons-halflings.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
img/grid.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
img/quickstart.png
Normal file
After Width: | Height: | Size: 38 KiB |
BIN
img/rest-framework-docs.png
Normal file
After Width: | Height: | Size: 75 KiB |
BIN
img/self-describing.png
Normal file
After Width: | Height: | Size: 53 KiB |
BIN
img/slate.png
Normal file
After Width: | Height: | Size: 64 KiB |
449
index.html
Normal file
|
@ -0,0 +1,449 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - APIs made easy</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Django REST framework">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="index-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 " href="tutorial/quickstart.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small disabled" href="#"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#django-rest-framework">Django REST framework</a></li>
|
||||||
|
<li><a href="#requirements">Requirements</a></li>
|
||||||
|
<li><a href="#installation">Installation</a></li>
|
||||||
|
<li><a href="#example">Example</a></li>
|
||||||
|
<li><a href="#quickstart">Quickstart</a></li>
|
||||||
|
<li><a href="#tutorial">Tutorial</a></li>
|
||||||
|
<li><a href="#api-guide">API Guide</a></li>
|
||||||
|
<li><a href="#topics">Topics</a></li>
|
||||||
|
<li><a href="#development">Development</a></li>
|
||||||
|
<li><a href="#support">Support</a></li>
|
||||||
|
<li><a href="#security">Security</a></li>
|
||||||
|
<li><a href="#license">License</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<p class="badges">
|
||||||
|
<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&repo=django-rest-framework&type=watch&count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
|
||||||
|
|
||||||
|
<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none"></a>
|
||||||
|
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
|
||||||
|
|
||||||
|
<img src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h1 id="django-rest-framework">Django REST framework</h1>
|
||||||
|
<p><strong>Awesome web-browsable Web APIs.</strong></p>
|
||||||
|
<p>Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.</p>
|
||||||
|
<p>Some reasons you might want to use REST framework:</p>
|
||||||
|
<ul>
|
||||||
|
<li>The <a href="http://restframework.herokuapp.com/">Web browseable API</a> is a huge usability win for your developers.</li>
|
||||||
|
<li><a href="api-guide/authentication.html">Authentication policies</a> including <a href="api-guide/authentication.html#oauthauthentication">OAuth1a</a> and <a href="api-guide/authentication.html#oauth2authentication">OAuth2</a> out of the box.</li>
|
||||||
|
<li><a href="api-guide/serializers.html">Serialization</a> that supports both <a href="api-guide/serializers.html#modelserializer">ORM</a> and <a href="api-guide/serializers.html#serializers">non-ORM</a> data sources.</li>
|
||||||
|
<li>Customizable all the way down - just use <a href="api-guide/views.html#function-based-views">regular function-based views</a> if you don't need the <a href="api-guide/generic-views.html">more</a> <a href="api-guide/viewsets.html">powerful</a> <a href="api-guide/routers.html">features</a>.</li>
|
||||||
|
<li><a href=".">Extensive documentation</a>, and <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">great community support</a>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>There is a live example API for testing purposes, <a href="http://restframework.herokuapp.com/">available here</a>.</p>
|
||||||
|
<p><strong>Below</strong>: <em>Screenshot from the browsable API</em></p>
|
||||||
|
<p><img alt="Screenshot" src="img/quickstart.png" /></p>
|
||||||
|
<h2 id="requirements">Requirements</h2>
|
||||||
|
<p>REST framework requires the following:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Python (2.6.5+, 2.7, 3.2, 3.3)</li>
|
||||||
|
<li>Django (1.3, 1.4, 1.5, 1.6)</li>
|
||||||
|
</ul>
|
||||||
|
<p>The following packages are optional:</p>
|
||||||
|
<ul>
|
||||||
|
<li><a href="http://pypi.python.org/pypi/Markdown/">Markdown</a> (2.1.0+) - Markdown support for the browsable API.</li>
|
||||||
|
<li><a href="http://pypi.python.org/pypi/PyYAML">PyYAML</a> (3.10+) - YAML content-type support.</li>
|
||||||
|
<li><a href="https://pypi.python.org/pypi/defusedxml">defusedxml</a> (0.3+) - XML content-type support.</li>
|
||||||
|
<li><a href="http://pypi.python.org/pypi/django-filter">django-filter</a> (0.5.4+) - Filtering support.</li>
|
||||||
|
<li><a href="https://bitbucket.org/david/django-oauth-plus/wiki/Home">django-oauth-plus</a> (2.0+) and <a href="https://github.com/simplegeo/python-oauth2">oauth2</a> (1.5.211+) - OAuth 1.0a support.</li>
|
||||||
|
<li><a href="https://github.com/caffeinehit/django-oauth2-provider">django-oauth2-provider</a> (0.2.3+) - OAuth 2.0 support.</li>
|
||||||
|
<li><a href="https://github.com/lukaszb/django-guardian">django-guardian</a> (1.1.1+) - Object level permissions support.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note</strong>: The <code>oauth2</code> Python package is badly misnamed, and actually provides OAuth 1.0a support. Also note that packages required for both OAuth 1.0a, and OAuth 2.0 are not yet Python 3 compatible.</p>
|
||||||
|
<h2 id="installation">Installation</h2>
|
||||||
|
<p>Install using <code>pip</code>, including any optional packages you want...</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>pip install djangorestframework
|
||||||
|
pip install markdown # Markdown support for the browsable API.
|
||||||
|
pip install django-filter # Filtering support
|
||||||
|
</code></pre>
|
||||||
|
<p>...or clone the project from github.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>git clone git@github.com:tomchristie/django-rest-framework.git
|
||||||
|
</code></pre>
|
||||||
|
<p>Add <code>'rest_framework'</code> to your <code>INSTALLED_APPS</code> setting.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>INSTALLED_APPS = (
|
||||||
|
...
|
||||||
|
'rest_framework',
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root <code>urls.py</code> file.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>urlpatterns = patterns('',
|
||||||
|
...
|
||||||
|
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that the URL path can be whatever you want, but you must include <code>'rest_framework.urls'</code> with the <code>'rest_framework'</code> namespace.</p>
|
||||||
|
<h2 id="example">Example</h2>
|
||||||
|
<p>Let's take a look at a quick example of using REST framework to build a simple model-backed API.</p>
|
||||||
|
<p>We'll create a read-write API for accessing users and groups.</p>
|
||||||
|
<p>Any global settings for a REST framework API are kept in a single configuration dictionary named <code>REST_FRAMEWORK</code>. Start off by adding the following to your <code>settings.py</code> module:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
# Use hyperlinked styles by default.
|
||||||
|
# Only used if the `serializer_class` attribute is not set on a view.
|
||||||
|
'DEFAULT_MODEL_SERIALIZER_CLASS':
|
||||||
|
'rest_framework.serializers.HyperlinkedModelSerializer',
|
||||||
|
|
||||||
|
# Use Django's standard `django.contrib.auth` permissions,
|
||||||
|
# or allow read-only access for unauthenticated users.
|
||||||
|
'DEFAULT_PERMISSION_CLASSES': [
|
||||||
|
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Don't forget to make sure you've also added <code>rest_framework</code> to your <code>INSTALLED_APPS</code>.</p>
|
||||||
|
<p>We're ready to create our API now.
|
||||||
|
Here's our project's root <code>urls.py</code> module:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.conf.urls.defaults import url, patterns, include
|
||||||
|
from django.contrib.auth.models import User, Group
|
||||||
|
from rest_framework import viewsets, routers
|
||||||
|
|
||||||
|
# ViewSets define the view behavior.
|
||||||
|
class UserViewSet(viewsets.ModelViewSet):
|
||||||
|
model = User
|
||||||
|
|
||||||
|
class GroupViewSet(viewsets.ModelViewSet):
|
||||||
|
model = Group
|
||||||
|
|
||||||
|
|
||||||
|
# Routers provide an easy way of automatically determining the URL conf
|
||||||
|
router = routers.DefaultRouter()
|
||||||
|
router.register(r'users', UserViewSet)
|
||||||
|
router.register(r'groups', GroupViewSet)
|
||||||
|
|
||||||
|
|
||||||
|
# Wire up our API using automatic URL routing.
|
||||||
|
# Additionally, we include login URLs for the browseable API.
|
||||||
|
urlpatterns = patterns('',
|
||||||
|
url(r'^', include(router.urls)),
|
||||||
|
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="quickstart">Quickstart</h2>
|
||||||
|
<p>Can't wait to get started? The <a href="tutorial/quickstart.html">quickstart guide</a> is the fastest way to get up and running, and building APIs with REST framework.</p>
|
||||||
|
<h2 id="tutorial">Tutorial</h2>
|
||||||
|
<p>The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.</p>
|
||||||
|
<ul>
|
||||||
|
<li><a href="tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="tutorial/2-requests-and-responses.html">2 - Requests & Responses</a></li>
|
||||||
|
<li><a href="tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="tutorial/4-authentication-and-permissions.html">4 - Authentication & permissions</a></li>
|
||||||
|
<li><a href="tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships & hyperlinked APIs</a></li>
|
||||||
|
<li><a href="tutorial/6-viewsets-and-routers.html">6 - Viewsets & routers</a></li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="api-guide">API Guide</h2>
|
||||||
|
<p>The API guide is your complete reference manual to all the functionality provided by REST framework.</p>
|
||||||
|
<ul>
|
||||||
|
<li><a href="api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="api-guide/settings.html">Settings</a></li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="topics">Topics</h2>
|
||||||
|
<p>General guides to using REST framework.</p>
|
||||||
|
<ul>
|
||||||
|
<li><a href="topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="development">Development</h2>
|
||||||
|
<p>If you want to work on REST framework itself, clone the repository, then...</p>
|
||||||
|
<p>Build the docs:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>./mkdocs.py
|
||||||
|
</code></pre>
|
||||||
|
<p>Run the tests:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>./rest_framework/runtests/runtests.py
|
||||||
|
</code></pre>
|
||||||
|
<p>To run the tests against all supported configurations, first install <a href="http://testrun.org/tox/latest/">the tox testing tool</a> globally, using <code>pip install tox</code>, then simply run <code>tox</code>: </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>tox
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="support">Support</h2>
|
||||||
|
<p>For support please see the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">REST framework discussion group</a>, try the <code>#restframework</code> channel on <code>irc.freenode.net</code>, search <a href="https://botbot.me/freenode/restframework/">the IRC archives</a>, or raise a question on <a href="http://stackoverflow.com/">Stack Overflow</a>, making sure to include the <a href="http://stackoverflow.com/questions/tagged/django-rest-framework">'django-rest-framework'</a> tag.</p>
|
||||||
|
<p><a href="http://dabapps.com/services/build/api-development/">Paid support is available</a> from <a href="http://dabapps.com">DabApps</a>, and can include work on REST framework core, or support with building your REST framework API. Please <a href="http://dabapps.com/contact/">contact DabApps</a> if you'd like to discuss commercial support options.</p>
|
||||||
|
<p>For updates on REST framework development, you may also want to follow <a href="https://twitter.com/_tomchristie">the author</a> on Twitter.</p>
|
||||||
|
<p><a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
|
||||||
|
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></p>
|
||||||
|
<h2 id="security">Security</h2>
|
||||||
|
<p>If you believe you’ve found something in Django REST framework which has security implications, please <strong>do not raise the issue in a public forum</strong>.</p>
|
||||||
|
<p>Send a description of the issue via email to <a href="mailto:rest-framework-security@googlegroups.com">rest-framework-security@googlegroups.com</a>. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.</p>
|
||||||
|
<h2 id="license">License</h2>
|
||||||
|
<p>Copyright (c) 2011-2013, Tom Christie
|
||||||
|
All rights reserved.</p>
|
||||||
|
<p>Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:</p>
|
||||||
|
<p>Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
Redistributions in binary form must reproduce the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer in the documentation and/or
|
||||||
|
other materials provided with the distribution.</p>
|
||||||
|
<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||||
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
7
js/bootstrap-2.1.1-min.js
vendored
Executable file
2
js/jquery-1.8.1-min.js
vendored
Normal file
28
js/prettify-1.0.js
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
|
||||||
|
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
|
||||||
|
[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c<
|
||||||
|
f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&&
|
||||||
|
(j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r=
|
||||||
|
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length,
|
||||||
|
t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
|
||||||
|
"string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
|
||||||
|
l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
|
||||||
|
q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
|
||||||
|
q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
|
||||||
|
"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
|
||||||
|
a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
|
||||||
|
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value",
|
||||||
|
m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m=
|
||||||
|
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue=
|
||||||
|
j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
|
||||||
|
"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
|
||||||
|
H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
|
||||||
|
J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
|
||||||
|
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),
|
||||||
|
["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",
|
||||||
|
/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
|
||||||
|
["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",
|
||||||
|
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b=
|
||||||
|
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m,
|
||||||
|
250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",
|
||||||
|
PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
|
350
topics/2.2-announcement.html
Normal file
|
@ -0,0 +1,350 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - REST framework 2.2 announcement</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, REST framework 2.2 announcement">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="2.2-announcement-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 " href="../topics/2.3-announcement.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/rest-framework-2-announcement.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#rest-framework-22-announcement">REST framework 2.2 announcement</a></li>
|
||||||
|
<li><a href="#python-3-support">Python 3 support</a></li>
|
||||||
|
<li><a href="#deprecation-policy">Deprecation policy</a></li>
|
||||||
|
<li><a href="#community">Community</a></li>
|
||||||
|
<li><a href="#api-changes">API changes</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="rest-framework-22-announcement">REST framework 2.2 announcement</h1>
|
||||||
|
<p>The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.</p>
|
||||||
|
<h2 id="python-3-support">Python 3 support</h2>
|
||||||
|
<p>Thanks to some fantastic work from <a href="https://github.com/xordoquy">Xavier Ordoquy</a>, Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently <a href="https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3">considered experimental</a>.</p>
|
||||||
|
<p>Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.</p>
|
||||||
|
<p>If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's <a href="https://docs.djangoproject.com/en/dev/topics/python3/">Porting to Python 3</a> documentation.</p>
|
||||||
|
<p>Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with <a href="https://docs.djangoproject.com/en/dev/releases/1.5/#python-compatibility">Django 1.5's Python compatibility</a>.</p>
|
||||||
|
<h2 id="deprecation-policy">Deprecation policy</h2>
|
||||||
|
<p>We've now introduced an official deprecation policy, which is in line with <a href="https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy">Django's deprecation policy</a>. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.</p>
|
||||||
|
<p>The timeline for deprecation works as follows:</p>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<p>Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise <code>PendingDeprecationWarning</code> warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using <code>python -Wd manage.py test</code>, you'll be warned of any API changes you need to make.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>Version 2.3 will escalate these warnings to <code>DeprecationWarning</code>, which is loud by default.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>Version 2.4 will remove the deprecated bits of API entirely.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p>Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.</p>
|
||||||
|
<h2 id="community">Community</h2>
|
||||||
|
<p>As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in <a href="http://django-rest-framework.org/topics/credits.html">the credits</a>, is now at over <strong>one hundred individuals</strong>. Each name on that list represents at least one merged pull request, however large or small.</p>
|
||||||
|
<p>Our <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">mailing list</a> and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great <a href="https://github.com/marcgibbons/django-rest-framework-docs">django-rest-framework-docs</a> package from <a href="https://github.com/marcgibbons/">Marc Gibbons</a>.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="api-changes">API changes</h2>
|
||||||
|
<p>The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.</p>
|
||||||
|
<h3 id="cleaner-to-many-related-fields">Cleaner to-many related fields</h3>
|
||||||
|
<p>The <code>ManyRelatedField()</code> style is being deprecated in favor of a new <code>RelatedField(many=True)</code> syntax.</p>
|
||||||
|
<p>For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following: </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
questions = serializers.PrimaryKeyRelatedField(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
fields = ('username', 'questions')
|
||||||
|
</code></pre>
|
||||||
|
<p>The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.</p>
|
||||||
|
<p>The change also applies to serializers. If you have a nested serializer, you should start using <code>many=True</code> for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class TrackSerializer(serializer.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Track
|
||||||
|
fields = ('name', 'duration')
|
||||||
|
|
||||||
|
class AlbumSerializer(serializer.ModelSerializer):
|
||||||
|
tracks = TrackSerializer(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Album
|
||||||
|
fields = ('album_name', 'artist', 'tracks')
|
||||||
|
</code></pre>
|
||||||
|
<p>Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the <code>many=True</code> flag.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
||||||
|
serializer.data
|
||||||
|
</code></pre>
|
||||||
|
<p>This more explicit behavior on serializing and deserializing data <a href="https://github.com/tomchristie/django-rest-framework/issues/564">makes integration with non-ORM backends such as MongoDB easier</a>, as instances to be serialized can include the <code>__iter__</code> method, without incorrectly triggering list-based serialization, or requiring workarounds.</p>
|
||||||
|
<p>The implicit to-many behavior on serializers, and the <code>ManyRelatedField</code> style classes will continue to function, but will raise a <code>PendingDeprecationWarning</code>, which can be made visible using the <code>-Wd</code> flag.</p>
|
||||||
|
<p><strong>Note</strong>: If you need to forcibly turn off the implicit "<code>many=True</code> for <code>__iter__</code> objects" behavior, you can now do so by specifying <code>many=False</code>. This will become the default (instead of the current default of <code>None</code>) once the deprecation of the implicit behavior is finalised in version 2.4.</p>
|
||||||
|
<h3 id="cleaner-optional-relationships">Cleaner optional relationships</h3>
|
||||||
|
<p>Serializer relationships for nullable Foreign Keys will change from using the current <code>null=True</code> flag, to instead using <code>required=False</code>.</p>
|
||||||
|
<p>For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a <code>Serializer</code> class:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>current_company = serializers.HyperlinkedRelatedField(required=False)
|
||||||
|
</code></pre>
|
||||||
|
<p>This is in line both with the rest of the serializer fields API, and with Django's <code>Form</code> and <code>ModelForm</code> API.</p>
|
||||||
|
<p>Using <code>required</code> throughout the serializers API means you won't need to consider if a particular field should take <code>blank</code> or <code>null</code> arguments instead of <code>required</code>, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data. </p>
|
||||||
|
<p>The <code>null=True</code> argument will continue to function, and will imply <code>required=False</code>, but will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<h3 id="cleaner-charfield-syntax">Cleaner CharField syntax</h3>
|
||||||
|
<p>The <code>CharField</code> API previously took an optional <code>blank=True</code> argument, which was intended to differentiate between null CharField input, and blank CharField input.</p>
|
||||||
|
<p>In keeping with Django's CharField API, REST framework's <code>CharField</code> will only ever return the empty string, for missing or <code>None</code> inputs. The <code>blank</code> flag will no longer be in use, and you should instead just use the <code>required=<bool></code> flag. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>extra_details = CharField(required=False)
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>blank</code> keyword argument will continue to function, but will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<h3 id="simpler-object-level-permissions">Simpler object-level permissions</h3>
|
||||||
|
<p>Custom permissions classes previously used the signature <code>.has_permission(self, request, view, obj=None)</code>. This method would be called twice, firstly for the global permissions check, with the <code>obj</code> parameter set to <code>None</code>, and again for the object-level permissions check when appropriate, with the <code>obj</code> parameter set to the relevant model instance.</p>
|
||||||
|
<p>The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Global permission checks now use the <code>.has_permission(self, request, view)</code> signature.</li>
|
||||||
|
<li>Object-level permission checks use a new method <code>.has_object_permission(self, request, view, obj)</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>For example, the following custom permission class:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class IsOwner(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Custom permission to only allow owners of an object to view or edit it.
|
||||||
|
Model instances are expected to include an `owner` attribute.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def has_permission(self, request, view, obj=None):
|
||||||
|
if obj is None:
|
||||||
|
# Ignore global permissions check
|
||||||
|
return True
|
||||||
|
|
||||||
|
return obj.owner == request.user
|
||||||
|
</code></pre>
|
||||||
|
<p>Now becomes:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class IsOwner(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Custom permission to only allow owners of an object to view or edit it.
|
||||||
|
Model instances are expected to include an `owner` attribute.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def has_object_permission(self, request, view, obj):
|
||||||
|
return obj.owner == request.user
|
||||||
|
</code></pre>
|
||||||
|
<p>If you're overriding the <code>BasePermission</code> class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<p>Note also that the usage of the internal APIs for permission checking on the <code>View</code> class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.</p>
|
||||||
|
<h3 id="more-explicit-hyperlink-relations-behavior">More explicit hyperlink relations behavior</h3>
|
||||||
|
<p>When using a serializer with a <code>HyperlinkedRelatedField</code> or <code>HyperlinkedIdentityField</code>, the hyperlinks would previously use absolute URLs if the serializer context included a <code>'request'</code> key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.</p>
|
||||||
|
<p>From version 2.2 onwards, serializers with hyperlinked relationships <em>always</em> require a <code>'request'</code> key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
443
topics/2.3-announcement.html
Normal file
|
@ -0,0 +1,443 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - REST framework 2.3 announcement</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, REST framework 2.3 announcement, API Changes, Other notes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="2.3-announcement-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 " href="../topics/release-notes.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/2.2-announcement.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#rest-framework-23-announcement">REST framework 2.3 announcement</a></li>
|
||||||
|
<li><a href="#viewsets-and-routers">ViewSets and Routers</a></li>
|
||||||
|
<li><a href="#simpler-views">Simpler views</a></li>
|
||||||
|
<li><a href="#easier-serializers">Easier Serializers</a></li>
|
||||||
|
<li><a href="#more-flexible-filtering">More flexible filtering</a></li>
|
||||||
|
<li class="main"><a href="#api-changes">API Changes</a></li>
|
||||||
|
<li><a href="#simplified-generic-view-classes">Simplified generic view classes</a></li>
|
||||||
|
<li><a href="#simpler-url-lookups">Simpler URL lookups</a></li>
|
||||||
|
<li><a href="#fileuploadparser">FileUploadParser</a></li>
|
||||||
|
<li><a href="#decimalfield">DecimalField</a></li>
|
||||||
|
<li><a href="#modelserializers-and-reverse-relationships">ModelSerializers and reverse relationships</a></li>
|
||||||
|
<li><a href="#view-names-and-descriptions">View names and descriptions</a></li>
|
||||||
|
<li class="main"><a href="#other-notes">Other notes</a></li>
|
||||||
|
<li><a href="#more-explicit-style">More explicit style</a></li>
|
||||||
|
<li><a href="#django-13-support">Django 1.3 support</a></li>
|
||||||
|
<li><a href="#version-22-api-changes">Version 2.2 API changes</a></li>
|
||||||
|
<li><a href="#what-comes-next">What comes next?</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="rest-framework-23-announcement">REST framework 2.3 announcement</h1>
|
||||||
|
<p>REST framework 2.3 makes it even quicker and easier to build your Web APIs.</p>
|
||||||
|
<h2 id="viewsets-and-routers">ViewSets and Routers</h2>
|
||||||
|
<p>The 2.3 release introduces the <a href="../api-guide/viewsets.html">ViewSet</a> and <a href="../api-guide/routers.html">Router</a> classes.</p>
|
||||||
|
<p>A viewset is simply a type of class based view that allows you to group multiple views into a single common class.</p>
|
||||||
|
<p>Routers allow you to automatically determine the URLconf for your viewset classes.</p>
|
||||||
|
<p>As an example of just how simple REST framework APIs can now be, here's an API written in a single <code>urls.py</code> module:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>"""
|
||||||
|
A REST framework API for viewing and editing users and groups.
|
||||||
|
"""
|
||||||
|
from django.conf.urls.defaults import url, patterns, include
|
||||||
|
from django.contrib.auth.models import User, Group
|
||||||
|
from rest_framework import viewsets, routers
|
||||||
|
|
||||||
|
|
||||||
|
# ViewSets define the view behavior.
|
||||||
|
class UserViewSet(viewsets.ModelViewSet):
|
||||||
|
model = User
|
||||||
|
|
||||||
|
class GroupViewSet(viewsets.ModelViewSet):
|
||||||
|
model = Group
|
||||||
|
|
||||||
|
|
||||||
|
# Routers provide an easy way of automatically determining the URL conf
|
||||||
|
router = routers.DefaultRouter()
|
||||||
|
router.register(r'users', UserViewSet)
|
||||||
|
router.register(r'groups', GroupViewSet)
|
||||||
|
|
||||||
|
|
||||||
|
# Wire up our API using automatic URL routing.
|
||||||
|
# Additionally, we include login URLs for the browseable API.
|
||||||
|
urlpatterns = patterns('',
|
||||||
|
url(r'^', include(router.urls)),
|
||||||
|
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>The best place to get started with ViewSets and Routers is to take a look at the <a href="../tutorial/6-viewsets-and-routers.html">newest section in the tutorial</a>, which demonstrates their usage.</p>
|
||||||
|
<h2 id="simpler-views">Simpler views</h2>
|
||||||
|
<p>This release rationalises the API and implementation of the generic views, dropping the dependency on Django's <code>SingleObjectMixin</code> and <code>MultipleObjectMixin</code> classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.</p>
|
||||||
|
<p>This improvement is reflected in improved documentation for the <code>GenericAPIView</code> base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.</p>
|
||||||
|
<h2 id="easier-serializers">Easier Serializers</h2>
|
||||||
|
<p>REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.</p>
|
||||||
|
<p>The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the <code>fields</code> metadata of the serializer class.</p>
|
||||||
|
<p>For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class BlogSerializer(serializers.ModelSerializer):
|
||||||
|
comments = serializers.PrimaryKeyRelatedField(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Blog
|
||||||
|
fields = ('id', 'title', 'created', 'comments')
|
||||||
|
</code></pre>
|
||||||
|
<p>As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class BlogSerializer(serializers.ModelSerializer):
|
||||||
|
"""
|
||||||
|
Don't need to specify the 'comments' field explicitly anymore.
|
||||||
|
"""
|
||||||
|
class Meta:
|
||||||
|
model = Blog
|
||||||
|
fields = ('id', 'title', 'created', 'comments')
|
||||||
|
</code></pre>
|
||||||
|
<p>Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class BlogSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
"""
|
||||||
|
This is a hyperlinked serializer, which default to using
|
||||||
|
a field named 'url' as the primary identifier.
|
||||||
|
Note that we can now easily also add in the 'id' field.
|
||||||
|
"""
|
||||||
|
class Meta:
|
||||||
|
model = Blog
|
||||||
|
fields = ('url', 'id', 'title', 'created', 'comments')
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="more-flexible-filtering">More flexible filtering</h2>
|
||||||
|
<p>The <code>FILTER_BACKEND</code> setting has moved to pending deprecation, in favor of a <code>DEFAULT_FILTER_BACKENDS</code> setting that takes a <em>list</em> of filter backend classes, instead of a single filter backend class.</p>
|
||||||
|
<p>The generic view <code>filter_backend</code> attribute has also been moved to pending deprecation in favor of a <code>filter_backends</code> setting.</p>
|
||||||
|
<p>Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly.</p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="api-changes">API Changes</h1>
|
||||||
|
<h2 id="simplified-generic-view-classes">Simplified generic view classes</h2>
|
||||||
|
<p>The functionality provided by <code>SingleObjectAPIView</code> and <code>MultipleObjectAPIView</code> base classes has now been moved into the base class <code>GenericAPIView</code>. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary.</p>
|
||||||
|
<p>Additionally the base generic view no longer inherits from Django's <code>SingleObjectMixin</code> or <code>MultipleObjectMixin</code> classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase.</p>
|
||||||
|
<p>Using the <code>SingleObjectAPIView</code> and <code>MultipleObjectAPIView</code> base classes continues to be supported, but will raise a <code>PendingDeprecationWarning</code>. You should instead simply use <code>GenericAPIView</code> as the base for any generic view subclasses.</p>
|
||||||
|
<h3 id="removed-attributes">Removed attributes</h3>
|
||||||
|
<p>The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed.</p>
|
||||||
|
<ul>
|
||||||
|
<li>context_object_name</li>
|
||||||
|
<li>get_context_data()</li>
|
||||||
|
<li>get_context_object_name()</li>
|
||||||
|
</ul>
|
||||||
|
<p>The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed.</p>
|
||||||
|
<ul>
|
||||||
|
<li>paginator_class</li>
|
||||||
|
<li>get_paginator()</li>
|
||||||
|
<li>get_allow_empty()</li>
|
||||||
|
<li>get_slug_field()</li>
|
||||||
|
</ul>
|
||||||
|
<p>There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases.</p>
|
||||||
|
<p>Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy.</p>
|
||||||
|
<h3 id="simplified-methods">Simplified methods</h3>
|
||||||
|
<p>The <code>get_object</code> and <code>get_paginate_by</code> methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple.</p>
|
||||||
|
<p>Using an optional queryset with these methods continues to be supported, but will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<p>The <code>paginate_queryset</code> method no longer takes a <code>page_size</code> argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a <code>page</code> object with an appropriate page size, or returns <code>None</code>, if pagination is not configured for the view.</p>
|
||||||
|
<p>Using the <code>page_size</code> argument is still supported and will trigger the old-style return type, but will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<h3 id="deprecated-attributes">Deprecated attributes</h3>
|
||||||
|
<p>The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state.</p>
|
||||||
|
<ul>
|
||||||
|
<li>pk_url_kwarg = 'pk'</li>
|
||||||
|
<li>slug_url_kwarg = 'slug'</li>
|
||||||
|
<li>slug_field = 'slug'</li>
|
||||||
|
</ul>
|
||||||
|
<p>Their usage is replaced with a single attribute:</p>
|
||||||
|
<ul>
|
||||||
|
<li>lookup_field = 'pk'</li>
|
||||||
|
</ul>
|
||||||
|
<p>This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the <code>lookup_field</code> argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.</p>
|
||||||
|
<p>For example, a view with 'username' based lookup might look like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserDetail(generics.RetrieveAPIView):
|
||||||
|
lookup_field = 'username'
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>And would have the following entry in the urlconf:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code> url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
|
||||||
|
</code></pre>
|
||||||
|
<p>Usage of the old-style attributes continues to be supported, but will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<p>The <code>allow_empty</code> attribute is also deprecated. To use <code>allow_empty=False</code> style behavior you should explicitly override <code>get_queryset</code> and raise an <code>Http404</code> on empty querysets.</p>
|
||||||
|
<p>For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class DisallowEmptyQuerysetMixin(object):
|
||||||
|
def get_queryset(self):
|
||||||
|
queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset()
|
||||||
|
if not queryset.exists():
|
||||||
|
raise Http404
|
||||||
|
return queryset
|
||||||
|
</code></pre>
|
||||||
|
<p>In our opinion removing lesser-used attributes like <code>allow_empty</code> helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.</p>
|
||||||
|
<h2 id="simpler-url-lookups">Simpler URL lookups</h2>
|
||||||
|
<p>The <code>HyperlinkedRelatedField</code> class now takes a single optional <code>lookup_field</code> argument, that replaces the <code>pk_url_kwarg</code>, <code>slug_url_kwarg</code>, and <code>slug_field</code> arguments.</p>
|
||||||
|
<p>For example, you might have a field that references it's relationship by a hyperlink based on a slug field:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code> account = HyperlinkedRelatedField(read_only=True,
|
||||||
|
lookup_field='slug',
|
||||||
|
view_name='account-detail')
|
||||||
|
</code></pre>
|
||||||
|
<p>Usage of the old-style attributes continues to be supported, but will raise a <code>PendingDeprecationWarning</code>.</p>
|
||||||
|
<h2 id="fileuploadparser">FileUploadParser</h2>
|
||||||
|
<p>2.3 adds a <code>FileUploadParser</code> parser class, that supports raw file uploads, in addition to the existing multipart upload support.</p>
|
||||||
|
<h2 id="decimalfield">DecimalField</h2>
|
||||||
|
<p>2.3 introduces a <code>DecimalField</code> serializer field, which returns <code>Decimal</code> instances.</p>
|
||||||
|
<p>For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering <code>Decimal</code> instances to your renderer implementation.</p>
|
||||||
|
<h2 id="modelserializers-and-reverse-relationships">ModelSerializers and reverse relationships</h2>
|
||||||
|
<p>The support for adding reverse relationships to the <code>fields</code> option on a <code>ModelSerializer</code> class means that the <code>get_related_field</code> and <code>get_nested_field</code> method signatures have now changed.</p>
|
||||||
|
<p>In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now <code>(self, model_field, related_model, to_many)</code>. For reverse relationships <code>model_field</code> will be <code>None</code>.</p>
|
||||||
|
<p>The old-style signature will continue to function but will raise a <code>PendingDeprecationWarning</code>. </p>
|
||||||
|
<h2 id="view-names-and-descriptions">View names and descriptions</h2>
|
||||||
|
<p>The mechanics of how the names and descriptions used in the browseable API are generated has been modified and cleaned up somewhat.</p>
|
||||||
|
<p>If you've been customizing this behavior, for example perhaps to use <code>rst</code> markup for the browseable API, then you'll need to take a look at the implementation to see what updates you need to make.</p>
|
||||||
|
<p>Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated. </p>
|
||||||
|
<hr />
|
||||||
|
<h1 id="other-notes">Other notes</h1>
|
||||||
|
<h2 id="more-explicit-style">More explicit style</h2>
|
||||||
|
<p>The usage of <code>model</code> attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit <code>queryset</code> and <code>serializer_class</code> attributes.</p>
|
||||||
|
<p>For example, the following is now the recommended style for using generic views:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountListView(generics.RetrieveAPIView):
|
||||||
|
queryset = MyModel.objects.all()
|
||||||
|
serializer_class = MyModelSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>Using an explicit <code>queryset</code> and <code>serializer_class</code> attributes makes the functioning of the view more clear than using the shortcut <code>model</code> attribute.</p>
|
||||||
|
<p>It also makes the usage of the <code>get_queryset()</code> or <code>get_serializer_class()</code> methods more obvious.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountListView(generics.RetrieveAPIView):
|
||||||
|
serializer_class = MyModelSerializer
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
"""
|
||||||
|
Determine the queryset dynamically, depending on the
|
||||||
|
user making the request.
|
||||||
|
|
||||||
|
Note that overriding this method follows on more obviously now
|
||||||
|
that an explicit `queryset` attribute is the usual view style.
|
||||||
|
"""
|
||||||
|
return self.user.accounts
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="django-13-support">Django 1.3 support</h2>
|
||||||
|
<p>The 2.3.x release series will be the last series to provide compatibility with Django 1.3.</p>
|
||||||
|
<h2 id="version-22-api-changes">Version 2.2 API changes</h2>
|
||||||
|
<p>All API changes in 2.2 that previously raised <code>PendingDeprecationWarning</code> will now raise a <code>DeprecationWarning</code>, which is loud by default.</p>
|
||||||
|
<h2 id="what-comes-next">What comes next?</h2>
|
||||||
|
<ul>
|
||||||
|
<li>Support for read-write nested serializers is almost complete, and due to be released in the next few weeks.</li>
|
||||||
|
<li>Extra filter backends for searching and ordering of results are planned to be added shortly.</li>
|
||||||
|
</ul>
|
||||||
|
<p>The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
263
topics/ajax-csrf-cors.html
Normal file
|
@ -0,0 +1,263 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Working with AJAX, CSRF & CORS</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Working with AJAX, CSRF & CORS">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="ajax-csrf-cors-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 " href="../topics/browser-enhancements.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/documenting-your-api.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#working-with-ajax,-csrf-&-cors">Working with AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="#javascript-clients">Javascript clients</a></li>
|
||||||
|
<li><a href="#csrf-protection">CSRF protection</a></li>
|
||||||
|
<li><a href="#cors">CORS</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="working-with-ajax-csrf-cors">Working with AJAX, CSRF & CORS</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>"Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."</p>
|
||||||
|
<p>— <a href="http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html">Jeff Atwood</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<h2 id="javascript-clients">Javascript clients</h2>
|
||||||
|
<p>If you’re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.</p>
|
||||||
|
<p>AJAX requests that are made within the same context as the API they are interacting with will typically use <code>SessionAuthentication</code>. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.</p>
|
||||||
|
<p>AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as <code>TokenAuthentication</code>. </p>
|
||||||
|
<h2 id="csrf-protection">CSRF protection</h2>
|
||||||
|
<p><a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)">Cross Site Request Forgery</a> protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.</p>
|
||||||
|
<p>To guard against these type of attacks, you need to do two things:</p>
|
||||||
|
<ol>
|
||||||
|
<li>Ensure that the 'safe' HTTP operations, such as <code>GET</code>, <code>HEAD</code> and <code>OPTIONS</code> cannot be used to alter any server-side state.</li>
|
||||||
|
<li>Ensure that any 'unsafe' HTTP operations, such as <code>POST</code>, <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code>, always require a valid CSRF token. </li>
|
||||||
|
</ol>
|
||||||
|
<p>If you're using <code>SessionAuthentication</code> you'll need to include valid CSRF tokens for any <code>POST</code>, <code>PUT</code>, <code>PATCH</code> or <code>DELETE</code> operations.</p>
|
||||||
|
<p>In order to make AJAX requests, you need to include CSRF token in the HTTP header, as <a href="https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax">described in the Django documentation</a>.</p>
|
||||||
|
<h2 id="cors">CORS</h2>
|
||||||
|
<p><a href="http://www.w3.org/TR/cors/">Cross-Origin Resource Sharing</a> is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.</p>
|
||||||
|
<p>The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.</p>
|
||||||
|
<p><a href="https://github.com/ottoyiu/">Otto Yiu</a> maintains the <a href="https://github.com/ottoyiu/django-cors-headers/">django-cors-headers</a> package, which is known to work correctly with REST framework APIs.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
357
topics/browsable-api.html
Normal file
|
@ -0,0 +1,357 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - The Browsable API</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, The Browsable API">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="browsable-api-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 " href="../topics/rest-hypermedia-hateoas.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/browser-enhancements.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#the-browsable-api">The Browsable API</a></li>
|
||||||
|
<li><a href="#urls">URLs</a></li>
|
||||||
|
<li><a href="#formats">Formats</a></li>
|
||||||
|
<li><a href="#customizing">Customizing</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="the-browsable-api">The Browsable API</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.</p>
|
||||||
|
<p>— <a href="http://en.wikiquote.org/wiki/Alfred_North_Whitehead">Alfred North Whitehead</a>, An Introduction to Mathematics (1911)</p>
|
||||||
|
</blockquote>
|
||||||
|
<p>API may stand for Application <em>Programming</em> Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the <code>HTML</code> format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using <code>POST</code>, <code>PUT</code>, and <code>DELETE</code>.</p>
|
||||||
|
<h2 id="urls">URLs</h2>
|
||||||
|
<p>If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The <code>rest_framework</code> package includes a <a href="../api-guide/reverse.html"><code>reverse</code></a> helper for this purpose.</p>
|
||||||
|
<h2 id="formats">Formats</h2>
|
||||||
|
<p>By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using <code>?format=</code> in the request, so you can look at the raw JSON response in a browser by adding <code>?format=json</code> to the URL. There are helpful extensions for viewing JSON in <a href="https://addons.mozilla.org/en-US/firefox/addon/jsonview/">Firefox</a> and <a href="https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc">Chrome</a>.</p>
|
||||||
|
<h2 id="customizing">Customizing</h2>
|
||||||
|
<p>The browsable API is built with <a href="http://getbootstrap.com">Twitter's Bootstrap</a> (v 2.1.1), making it easy to customize the look-and-feel.</p>
|
||||||
|
<p>To customize the default style, create a template called <code>rest_framework/api.html</code> that extends from <code>rest_framework/base.html</code>. For example:</p>
|
||||||
|
<p><strong>templates/rest_framework/api.html</strong></p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{% extends "rest_framework/base.html" %}
|
||||||
|
|
||||||
|
... # Override blocks with required customizations
|
||||||
|
</code></pre>
|
||||||
|
<h3 id="overriding-the-default-theme">Overriding the default theme</h3>
|
||||||
|
<p>To replace the default theme, add a <code>bootstrap_theme</code> block to your <code>api.html</code> and insert a <code>link</code> to the desired Bootstrap theme css file. This will completely replace the included theme.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{% block bootstrap_theme %}
|
||||||
|
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
||||||
|
{% endblock %}
|
||||||
|
</code></pre>
|
||||||
|
<p>A suitable replacement theme can be generated using Bootstrap's <a href="http://twitter.github.com/bootstrap/customize.html#variables">Customize Tool</a>. There are also pre-made themes available at <a href="http://bootswatch.com/">Bootswatch</a>. To use any of the Bootswatch themes, simply download the theme's <code>bootstrap.min.css</code> file, add it to your project, and replace the default one as described above.</p>
|
||||||
|
<p>You can also change the navbar variant, which by default is <code>navbar-inverse</code>, using the <code>bootstrap_navbar_variant</code> block. The empty <code>{% block bootstrap_navbar_variant %}{% endblock %}</code> will use the original Bootstrap navbar style.</p>
|
||||||
|
<p>Full example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{% extends "rest_framework/base.html" %}
|
||||||
|
|
||||||
|
{% block bootstrap_theme %}
|
||||||
|
<link rel="stylesheet" href="http://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block bootstrap_navbar_variant %}{% endblock %}
|
||||||
|
</code></pre>
|
||||||
|
<p>For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the <code>style</code> block.</p>
|
||||||
|
<hr />
|
||||||
|
<p><img alt="Cerulean theme" src="../img/cerulean.png" /></p>
|
||||||
|
<p><em>Screenshot of the bootswatch 'Cerulean' theme</em></p>
|
||||||
|
<hr />
|
||||||
|
<p><img alt="Slate theme" src="../img/slate.png" /></p>
|
||||||
|
<p><em>Screenshot of the bootswatch 'Slate' theme</em></p>
|
||||||
|
<hr />
|
||||||
|
<h3 id="blocks">Blocks</h3>
|
||||||
|
<p>All of the blocks available in the browsable API base template that can be used in your <code>api.html</code>.</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>bodyclass</code> - Class attribute for the <code><body></code> tag, empty by default.</li>
|
||||||
|
<li><code>bootstrap_theme</code> - CSS for the Bootstrap theme.</li>
|
||||||
|
<li><code>bootstrap_navbar_variant</code> - CSS class for the navbar.</li>
|
||||||
|
<li><code>branding</code> - Branding section of the navbar, see <a href="http://twitter.github.com/bootstrap/components.html#navbar">Bootstrap components</a>.</li>
|
||||||
|
<li><code>breadcrumbs</code> - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.</li>
|
||||||
|
<li><code>footer</code> - Any copyright notices or similar footer materials can go here (by default right-aligned).</li>
|
||||||
|
<li><code>script</code> - JavaScript files for the page.</li>
|
||||||
|
<li><code>style</code> - CSS stylesheets for the page.</li>
|
||||||
|
<li><code>title</code> - Title of the page.</li>
|
||||||
|
<li><code>userlinks</code> - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use <code>{{ block.super }}</code> to preserve the authentication links.</li>
|
||||||
|
</ul>
|
||||||
|
<h4 id="components">Components</h4>
|
||||||
|
<p>All of the standard <a href="http://twitter.github.com/bootstrap/components.html">Bootstrap components</a> are available.</p>
|
||||||
|
<h4 id="tooltips">Tooltips</h4>
|
||||||
|
<p>The browsable API makes use of the Bootstrap tooltips component. Any element with the <code>js-tooltip</code> class and a <code>title</code> attribute has that title content will display a tooltip on hover events.</p>
|
||||||
|
<h3 id="login-template">Login Template</h3>
|
||||||
|
<p>To add branding and customize the look-and-feel of the login template, create a template called <code>login.html</code> and add it to your project, eg: <code>templates/rest_framework/login.html</code>. The template should extend from <code>rest_framework/login_base.html</code>.</p>
|
||||||
|
<p>You can add your site name or branding by including the branding block:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{% block branding %}
|
||||||
|
<h3 style="margin: 0 0 20px;">My Site Name</h3>
|
||||||
|
{% endblock %}
|
||||||
|
</code></pre>
|
||||||
|
<p>You can also customize the style by adding the <code>bootstrap_theme</code> or <code>style</code> block similar to <code>api.html</code>.</p>
|
||||||
|
<h3 id="advanced-customization">Advanced Customization</h3>
|
||||||
|
<h4 id="context">Context</h4>
|
||||||
|
<p>The context that's available to the template:</p>
|
||||||
|
<ul>
|
||||||
|
<li><code>allowed_methods</code> : A list of methods allowed by the resource</li>
|
||||||
|
<li><code>api_settings</code> : The API settings</li>
|
||||||
|
<li><code>available_formats</code> : A list of formats allowed by the resource</li>
|
||||||
|
<li><code>breadcrumblist</code> : The list of links following the chain of nested resources</li>
|
||||||
|
<li><code>content</code> : The content of the API response</li>
|
||||||
|
<li><code>description</code> : The description of the resource, generated from its docstring</li>
|
||||||
|
<li><code>name</code> : The name of the resource</li>
|
||||||
|
<li><code>post_form</code> : A form instance for use by the POST form (if allowed)</li>
|
||||||
|
<li><code>put_form</code> : A form instance for use by the PUT form (if allowed)</li>
|
||||||
|
<li><code>display_edit_forms</code> : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed</li>
|
||||||
|
<li><code>request</code> : The request object</li>
|
||||||
|
<li><code>response</code> : The response object</li>
|
||||||
|
<li><code>version</code> : The version of Django REST Framework</li>
|
||||||
|
<li><code>view</code> : The view handling the request</li>
|
||||||
|
<li><code>FORMAT_PARAM</code> : The view can accept a format override</li>
|
||||||
|
<li><code>METHOD_PARAM</code> : The view can accept a method override</li>
|
||||||
|
</ul>
|
||||||
|
<p>You can override the <code>BrowsableAPIRenderer.get_context()</code> method to customise the context that gets passed to the template.</p>
|
||||||
|
<h4 id="not-using-basehtml">Not using base.html</h4>
|
||||||
|
<p>For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have <code>api.html</code> extend <code>base.html</code>. Then the page content and capabilities are entirely up to you.</p>
|
||||||
|
<h4 id="autocompletion">Autocompletion</h4>
|
||||||
|
<p>When a <code>ChoiceField</code> has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. One solution is to replace the selector by an autocomplete widget, that only loads and renders a subset of the available options as needed.</p>
|
||||||
|
<p>There are <a href="https://www.djangopackages.com/grids/g/auto-complete/">a variety of packages for autocomplete widgets</a>, such as <a href="https://github.com/yourlabs/django-autocomplete-light">django-autocomplete-light</a>. To setup <code>django-autocomplete-light</code>, follow the <a href="http://django-autocomplete-light.readthedocs.org/en/latest/#install">installation documentation</a>, add the the following to the <code>api.html</code> template:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{% block script %}
|
||||||
|
{{ block.super }}
|
||||||
|
{% include 'autocomplete_light/static.html' %}
|
||||||
|
{% endblock %}
|
||||||
|
</code></pre>
|
||||||
|
<p>You can now add the <code>autocomplete_light.ChoiceWidget</code> widget to the serializer field.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>import autocomplete_light
|
||||||
|
|
||||||
|
class BookSerializer(serializers.ModelSerializer):
|
||||||
|
author = serializers.ChoiceField(
|
||||||
|
widget=autocomplete_light.ChoiceWidget('AuthorAutocomplete')
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Book
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<p><img alt="Autocomplete" src="../img/autocomplete.png" /></p>
|
||||||
|
<p><em>Screenshot of the autocomplete-light widget</em></p>
|
||||||
|
<hr />
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
297
topics/browser-enhancements.html
Normal file
|
@ -0,0 +1,297 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Browser enhancements</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Browser enhancements">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="browser-enhancements-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 " href="../topics/browsable-api.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/ajax-csrf-cors.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#browser-enhancements">Browser enhancements</a></li>
|
||||||
|
<li><a href="#browser-based-put,-delete,-etc">Browser based PUT, DELETE, etc...</a></li>
|
||||||
|
<li><a href="#http-header-based-method-overriding">HTTP header based method overriding</a></li>
|
||||||
|
<li><a href="#browser-based-submission-of-non-form-content">Browser based submission of non-form content</a></li>
|
||||||
|
<li><a href="#url-based-accept-headers">URL based accept headers</a></li>
|
||||||
|
<li><a href="#url-based-format-suffixes">URL based format suffixes</a></li>
|
||||||
|
<li><a href="#doesnt-html5-support-put-and-delete-forms">Doesn't HTML5 support PUT and DELETE forms?</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="browser-enhancements">Browser enhancements</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>"There are two noncontroversial uses for overloaded POST. The first is to <em>simulate</em> HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"</p>
|
||||||
|
<p>— <a href="http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260">RESTful Web Services</a>, Leonard Richardson & Sam Ruby.</p>
|
||||||
|
</blockquote>
|
||||||
|
<h2 id="browser-based-put-delete-etc">Browser based PUT, DELETE, etc...</h2>
|
||||||
|
<p>REST framework supports browser-based <code>PUT</code>, <code>DELETE</code> and other methods, by
|
||||||
|
overloading <code>POST</code> requests using a hidden form field.</p>
|
||||||
|
<p>Note that this is the same strategy as is used in <a href="http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work">Ruby on Rails</a>.</p>
|
||||||
|
<p>For example, given the following form:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code><form action="/news-items/5" method="POST">
|
||||||
|
<input type="hidden" name="_method" value="DELETE">
|
||||||
|
</form>
|
||||||
|
</code></pre>
|
||||||
|
<p><code>request.method</code> would return <code>"DELETE"</code>.</p>
|
||||||
|
<h2 id="http-header-based-method-overriding">HTTP header based method overriding</h2>
|
||||||
|
<p>REST framework also supports method overriding via the semi-standard <code>X-HTTP-Method-Override</code> header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as <code>PATCH</code>. For example <a href="https://forums.aws.amazon.com/thread.jspa?messageID=400724">Amazon Web Services ELB</a>.</p>
|
||||||
|
<p>To use it, make a <code>POST</code> request, setting the <code>X-HTTP-Method-Override</code> header.</p>
|
||||||
|
<p>For example, making a <code>PATCH</code> request via <code>POST</code> in jQuery:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>$.ajax({
|
||||||
|
url: '/myresource/',
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'X-HTTP-Method-Override': 'PATCH'},
|
||||||
|
...
|
||||||
|
});
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="browser-based-submission-of-non-form-content">Browser based submission of non-form content</h2>
|
||||||
|
<p>Browser-based submission of content types other than form are supported by
|
||||||
|
using form fields named <code>_content</code> and <code>_content_type</code>:</p>
|
||||||
|
<p>For example, given the following form:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code><form action="/news-items/5" method="PUT">
|
||||||
|
<input type="hidden" name="_content_type" value="application/json">
|
||||||
|
<input name="_content" value="{'count': 1}">
|
||||||
|
</form>
|
||||||
|
</code></pre>
|
||||||
|
<p><code>request.content_type</code> would return <code>"application/json"</code>, and
|
||||||
|
<code>request.stream</code> would return <code>"{'count': 1}"</code></p>
|
||||||
|
<h2 id="url-based-accept-headers">URL based accept headers</h2>
|
||||||
|
<p>REST framework can take <code>?accept=application/json</code> style URL parameters,
|
||||||
|
which allow the <code>Accept</code> header to be overridden.</p>
|
||||||
|
<p>This can be useful for testing the API from a web browser, where you don't
|
||||||
|
have any control over what is sent in the <code>Accept</code> header.</p>
|
||||||
|
<h2 id="url-based-format-suffixes">URL based format suffixes</h2>
|
||||||
|
<p>REST framework can take <code>?format=json</code> style URL parameters, which can be a
|
||||||
|
useful shortcut for determining which content type should be returned from
|
||||||
|
the view.</p>
|
||||||
|
<p>This is a more concise than using the <code>accept</code> override, but it also gives
|
||||||
|
you less control. (For example you can't specify any media type parameters)</p>
|
||||||
|
<h2 id="doesnt-html5-support-put-and-delete-forms">Doesn't HTML5 support PUT and DELETE forms?</h2>
|
||||||
|
<p>Nope. It was at one point intended to support <code>PUT</code> and <code>DELETE</code> forms, but
|
||||||
|
was later <a href="http://www.w3.org/TR/html5-diff/#changes-2010-06-24">dropped from the spec</a>. There remains
|
||||||
|
<a href="http://amundsen.com/examples/put-delete-forms/">ongoing discussion</a> about adding support for <code>PUT</code> and <code>DELETE</code>,
|
||||||
|
as well as how to support content types other than form-encoded data.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
351
topics/contributing.html
Normal file
|
@ -0,0 +1,351 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Contributing to REST framework</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Contributing to REST framework, Community, Issues, Development, Testing, Documentation, Third party packages, Core committers">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="contributing-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 " href="../topics/rest-framework-2-announcement.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/rest-hypermedia-hateoas.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#contributing-to-rest-framework">Contributing to REST framework</a></li>
|
||||||
|
<li class="main"><a href="#community">Community</a></li>
|
||||||
|
<li class="main"><a href="#issues">Issues</a></li>
|
||||||
|
<li class="main"><a href="#development">Development</a></li>
|
||||||
|
<li class="main"><a href="#testing">Testing</a></li>
|
||||||
|
<li class="main"><a href="#documentation">Documentation</a></li>
|
||||||
|
<li><a href="#building-the-documentation">Building the documentation</a></li>
|
||||||
|
<li><a href="#language-style">Language style</a></li>
|
||||||
|
<li><a href="#markdown-style">Markdown style</a></li>
|
||||||
|
<li class="main"><a href="#third-party-packages">Third party packages</a></li>
|
||||||
|
<li class="main"><a href="#core-committers">Core committers</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="contributing-to-rest-framework">Contributing to REST framework</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>The world can only really be changed one piece at a time. The art is picking that piece.</p>
|
||||||
|
<p>— <a href="http://www.w3.org/People/Berners-Lee/FAQ.html">Tim Berners-Lee</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.</p>
|
||||||
|
<h1 id="community">Community</h1>
|
||||||
|
<p>If you use and enjoy REST framework please consider <a href="https://github.com/tomchristie/django-rest-framework">staring the project on GitHub</a>, and <a href="https://www.djangopackages.com/grids/g/api/">upvoting it on Django packages</a>. Doing so helps potential new users see that the project is well used, and help us continue to attract new users.</p>
|
||||||
|
<p>You might also consider writing a blog post on your experience with using REST framework, writing a tutorial about using the project with a particular javascript framework, or simply sharing the love on Twitter.</p>
|
||||||
|
<p>Other really great ways you can help move the community forward include helping answer questions on the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">discussion group</a>, or setting up an <a href="http://stackexchange.com/filters/66475/rest-framework">email alert on StackOverflow</a> so that you get notified of any new questions with the <code>django-rest-framework</code> tag.</p>
|
||||||
|
<p>When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant. </p>
|
||||||
|
<h1 id="issues">Issues</h1>
|
||||||
|
<p>It's really helpful if you make sure you address issues to the correct channel. Usage questions should be directed to the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">discussion group</a>. Feature requests, bug reports and other issues should be raised on the GitHub <a href="https://github.com/tomchristie/django-rest-framework/issues?state=open">issue tracker</a>.</p>
|
||||||
|
<p>Some tips on good issue reporting:</p>
|
||||||
|
<ul>
|
||||||
|
<li>When describing issues try to phrase your ticket in terms of the <em>behavior</em> you think needs changing rather than the <em>code</em> you think need changing.</li>
|
||||||
|
<li>Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.</li>
|
||||||
|
<li>
|
||||||
|
<p>If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>TODO: Triage</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<h1 id="development">Development</h1>
|
||||||
|
<ul>
|
||||||
|
<li>git clone & PYTHONPATH</li>
|
||||||
|
<li>Pep8</li>
|
||||||
|
<li>Recommend editor that runs pep8</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="pull-requests">Pull requests</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Make pull requests early</li>
|
||||||
|
<li>Describe branching</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="managing-compatibility-issues">Managing compatibility issues</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Describe compat module</li>
|
||||||
|
</ul>
|
||||||
|
<h1 id="testing">Testing</h1>
|
||||||
|
<ul>
|
||||||
|
<li>Running the tests</li>
|
||||||
|
<li>tox</li>
|
||||||
|
</ul>
|
||||||
|
<h1 id="documentation">Documentation</h1>
|
||||||
|
<p>The documentation for REST framework is built from the <a href="http://daringfireball.net/projects/markdown/basics">Markdown</a> source files in <a href="https://github.com/tomchristie/django-rest-framework/tree/master/docs">the docs directory</a>.</p>
|
||||||
|
<p>There are many great markdown editors that make working with the documentation really easy. The <a href="http://mouapp.com/">Mou editor for Mac</a> is one such editor that comes highly recommended.</p>
|
||||||
|
<h2 id="building-the-documentation">Building the documentation</h2>
|
||||||
|
<p>To build the documentation, simply run the <code>mkdocs.py</code> script.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>./mkdocs.py
|
||||||
|
</code></pre>
|
||||||
|
<p>This will build the html output into the <code>html</code> directory.</p>
|
||||||
|
<p>You can build the documentation and open a preview in a browser window by using the <code>-p</code> flag.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>./mkdocs.py -p
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="language-style">Language style</h2>
|
||||||
|
<p>Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.</p>
|
||||||
|
<p>Some other tips:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Keep paragraphs reasonably short.</li>
|
||||||
|
<li>Use double spacing after the end of sentences.</li>
|
||||||
|
<li>Don't use the abbreviations such as 'e.g..' but instead use long form, such as 'For example'.</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="markdown-style">Markdown style</h2>
|
||||||
|
<p>There are a couple of conventions you should follow when working on the documentation.</p>
|
||||||
|
<h5 id="1-headers">1. Headers</h5>
|
||||||
|
<p>Headers should use the hash style. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>### Some important topic
|
||||||
|
</code></pre>
|
||||||
|
<p>The underline style should not be used. <strong>Don't do this:</strong> </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>Some important topic
|
||||||
|
====================
|
||||||
|
</code></pre>
|
||||||
|
<h5 id="2-links">2. Links</h5>
|
||||||
|
<p>Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>Here is a link to [some other thing][other-thing].
|
||||||
|
|
||||||
|
More text...
|
||||||
|
|
||||||
|
[other-thing]: http://example.com/other/thing
|
||||||
|
</code></pre>
|
||||||
|
<p>This style helps keep the documentation source consistent and readable.</p>
|
||||||
|
<p>If you are hyperlinking to another REST framework document, you should use a relative link, and link to the <code>.md</code> suffix. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>[authentication]: ../api-guide/authentication.md
|
||||||
|
</code></pre>
|
||||||
|
<p>Linking in this style means you'll be able to click the hyperlink in your markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.</p>
|
||||||
|
<h5 id="3-notes">3. Notes</h5>
|
||||||
|
<p>If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>---
|
||||||
|
|
||||||
|
**Note:** Make sure you do this thing.
|
||||||
|
|
||||||
|
---
|
||||||
|
</code></pre>
|
||||||
|
<h1 id="third-party-packages">Third party packages</h1>
|
||||||
|
<ul>
|
||||||
|
<li>Django reusable app</li>
|
||||||
|
</ul>
|
||||||
|
<h1 id="core-committers">Core committers</h1>
|
||||||
|
<ul>
|
||||||
|
<li>Still use pull reqs</li>
|
||||||
|
<li>Credits</li>
|
||||||
|
</ul>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
432
topics/credits.html
Normal file
|
@ -0,0 +1,432 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Credits</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Credits">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="credits-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 disabled" href="#">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/release-notes.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#credits">Credits</a></li>
|
||||||
|
<li><a href="#additional-thanks">Additional thanks</a></li>
|
||||||
|
<li><a href="#contact">Contact</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="credits">Credits</h1>
|
||||||
|
<p>The following people have helped make REST framework great.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Tom Christie - <a href="https://github.com/tomchristie">tomchristie</a></li>
|
||||||
|
<li>Marko Tibold - <a href="https://github.com/markotibold">markotibold</a></li>
|
||||||
|
<li>Paul Miller - <a href="https://github.com/paulmillr">paulmillr</a></li>
|
||||||
|
<li>Sébastien Piquemal - <a href="https://github.com/sebpiq">sebpiq</a></li>
|
||||||
|
<li>Carmen Wick - <a href="https://github.com/cwick">cwick</a></li>
|
||||||
|
<li>Alex Ehlke - <a href="https://github.com/aehlke">aehlke</a></li>
|
||||||
|
<li>Alen Mujezinovic - <a href="https://github.com/flashingpumpkin">flashingpumpkin</a></li>
|
||||||
|
<li>Carles Barrobés - <a href="https://github.com/txels">txels</a></li>
|
||||||
|
<li>Michael Fötsch - <a href="https://github.com/mfoetsch">mfoetsch</a></li>
|
||||||
|
<li>David Larlet - <a href="https://github.com/david">david</a></li>
|
||||||
|
<li>Andrew Straw - <a href="https://github.com/astraw">astraw</a></li>
|
||||||
|
<li>Zeth - <a href="https://github.com/zeth">zeth</a></li>
|
||||||
|
<li>Fernando Zunino - <a href="https://github.com/fzunino">fzunino</a></li>
|
||||||
|
<li>Jens Alm - <a href="https://github.com/ulmus">ulmus</a></li>
|
||||||
|
<li>Craig Blaszczyk - <a href="https://github.com/jakul">jakul</a></li>
|
||||||
|
<li>Garcia Solero - <a href="https://github.com/garciasolero">garciasolero</a></li>
|
||||||
|
<li>Tom Drummond - <a href="https://github.com/devioustree">devioustree</a></li>
|
||||||
|
<li>Danilo Bargen - <a href="https://github.com/dbrgn">dbrgn</a></li>
|
||||||
|
<li>Andrew McCloud - <a href="https://github.com/amccloud">amccloud</a></li>
|
||||||
|
<li>Thomas Steinacher - <a href="https://github.com/thomasst">thomasst</a></li>
|
||||||
|
<li>Meurig Freeman - <a href="https://github.com/meurig">meurig</a></li>
|
||||||
|
<li>Anthony Nemitz - <a href="https://github.com/anemitz">anemitz</a></li>
|
||||||
|
<li>Ewoud Kohl van Wijngaarden - <a href="https://github.com/ekohl">ekohl</a></li>
|
||||||
|
<li>Michael Ding - <a href="https://github.com/yandy">yandy</a></li>
|
||||||
|
<li>Mjumbe Poe - <a href="https://github.com/mjumbewu">mjumbewu</a></li>
|
||||||
|
<li>Natim - <a href="https://github.com/natim">natim</a></li>
|
||||||
|
<li>Sebastian Żurek - <a href="https://github.com/sebzur">sebzur</a></li>
|
||||||
|
<li>Benoit C - <a href="https://github.com/dzen">dzen</a></li>
|
||||||
|
<li>Chris Pickett - <a href="https://github.com/bunchesofdonald">bunchesofdonald</a></li>
|
||||||
|
<li>Ben Timby - <a href="https://github.com/btimby">btimby</a></li>
|
||||||
|
<li>Michele Lazzeri - <a href="https://github.com/michelelazzeri-nextage">michelelazzeri-nextage</a></li>
|
||||||
|
<li>Camille Harang - <a href="https://github.com/mammique">mammique</a></li>
|
||||||
|
<li>Paul Oswald - <a href="https://github.com/poswald">poswald</a></li>
|
||||||
|
<li>Sean C. Farley - <a href="https://github.com/scfarley">scfarley</a></li>
|
||||||
|
<li>Daniel Izquierdo - <a href="https://github.com/izquierdo">izquierdo</a></li>
|
||||||
|
<li>Can Yavuz - <a href="https://github.com/tschan">tschan</a></li>
|
||||||
|
<li>Shawn Lewis - <a href="https://github.com/shawnlewis">shawnlewis</a></li>
|
||||||
|
<li>Alec Perkins - <a href="https://github.com/alecperkins">alecperkins</a></li>
|
||||||
|
<li>Michael Barrett - <a href="https://github.com/phobologic">phobologic</a></li>
|
||||||
|
<li>Mathieu Dhondt - <a href="https://github.com/laundromat">laundromat</a></li>
|
||||||
|
<li>Johan Charpentier - <a href="https://github.com/cyberj">cyberj</a></li>
|
||||||
|
<li>Jamie Matthews - <a href="https://github.com/j4mie">j4mie</a></li>
|
||||||
|
<li>Mattbo - <a href="https://github.com/mattbo">mattbo</a></li>
|
||||||
|
<li>Max Hurl - <a href="https://github.com/maximilianhurl">maximilianhurl</a></li>
|
||||||
|
<li>Tomi Pajunen - <a href="https://github.com/eofs">eofs</a></li>
|
||||||
|
<li>Rob Dobson - <a href="https://github.com/rdobson">rdobson</a></li>
|
||||||
|
<li>Daniel Vaca Araujo - <a href="https://github.com/diviei">diviei</a></li>
|
||||||
|
<li>Madis Väin - <a href="https://github.com/madisvain">madisvain</a></li>
|
||||||
|
<li>Stephan Groß - <a href="https://github.com/minddust">minddust</a></li>
|
||||||
|
<li>Pavel Savchenko - <a href="https://github.com/asfaltboy">asfaltboy</a></li>
|
||||||
|
<li>Otto Yiu - <a href="https://github.com/OttoYiu">ottoyiu</a></li>
|
||||||
|
<li>Jacob Magnusson - <a href="https://github.com/jmagnusson">jmagnusson</a></li>
|
||||||
|
<li>Osiloke Harold Emoekpere - <a href="https://github.com/osiloke">osiloke</a></li>
|
||||||
|
<li>Michael Shepanski - <a href="https://github.com/mjs7231">mjs7231</a></li>
|
||||||
|
<li>Toni Michel - <a href="https://github.com/tonimichel">tonimichel</a></li>
|
||||||
|
<li>Ben Konrath - <a href="https://github.com/benkonrath">benkonrath</a></li>
|
||||||
|
<li>Marc Aymerich - <a href="https://github.com/glic3rinu">glic3rinu</a></li>
|
||||||
|
<li>Ludwig Kraatz - <a href="https://github.com/ludwigkraatz">ludwigkraatz</a></li>
|
||||||
|
<li>Rob Romano - <a href="https://github.com/robromano">robromano</a></li>
|
||||||
|
<li>Eugene Mechanism - <a href="https://github.com/mechanism">mechanism</a></li>
|
||||||
|
<li>Jonas Liljestrand - <a href="https://github.com/jonlil">jonlil</a></li>
|
||||||
|
<li>Justin Davis - <a href="https://github.com/irrelative">irrelative</a></li>
|
||||||
|
<li>Dustin Bachrach - <a href="https://github.com/dbachrach">dbachrach</a></li>
|
||||||
|
<li>Mark Shirley - <a href="https://github.com/maspwr">maspwr</a></li>
|
||||||
|
<li>Olivier Aubert - <a href="https://github.com/oaubert">oaubert</a></li>
|
||||||
|
<li>Yuri Prezument - <a href="https://github.com/yprez">yprez</a></li>
|
||||||
|
<li>Fabian Buechler - <a href="https://github.com/fabianbuechler">fabianbuechler</a></li>
|
||||||
|
<li>Mark Hughes - <a href="https://github.com/mhsparks">mhsparks</a></li>
|
||||||
|
<li>Michael van de Waeter - <a href="https://github.com/mvdwaeter">mvdwaeter</a></li>
|
||||||
|
<li>Reinout van Rees - <a href="https://github.com/reinout">reinout</a></li>
|
||||||
|
<li>Michael Richards - <a href="https://github.com/justanotherbody">justanotherbody</a></li>
|
||||||
|
<li>Ben Roberts - <a href="https://github.com/roberts81">roberts81</a></li>
|
||||||
|
<li>Venkata Subramanian Mahalingam - <a href="https://github.com/annacoder">annacoder</a></li>
|
||||||
|
<li>George Kappel - <a href="https://github.com/gkappel">gkappel</a></li>
|
||||||
|
<li>Colin Murtaugh - <a href="https://github.com/cmurtaugh">cmurtaugh</a></li>
|
||||||
|
<li>Simon Pantzare - <a href="https://github.com/pilt">pilt</a></li>
|
||||||
|
<li>Szymon Teżewski - <a href="https://github.com/sunscrapers">sunscrapers</a></li>
|
||||||
|
<li>Joel Marcotte - <a href="https://github.com/joual">joual</a></li>
|
||||||
|
<li>Trey Hunner - <a href="https://github.com/treyhunner">treyhunner</a></li>
|
||||||
|
<li>Roman Akinfold - <a href="https://github.com/akinfold">akinfold</a></li>
|
||||||
|
<li>Toran Billups - <a href="https://github.com/toranb">toranb</a></li>
|
||||||
|
<li>Sébastien Béal - <a href="https://github.com/sebastibe">sebastibe</a></li>
|
||||||
|
<li>Andrew Hankinson - <a href="https://github.com/ahankinson">ahankinson</a></li>
|
||||||
|
<li>Juan Riaza - <a href="https://github.com/juanriaza">juanriaza</a></li>
|
||||||
|
<li>Michael Mior - <a href="https://github.com/michaelmior">michaelmior</a></li>
|
||||||
|
<li>Marc Tamlyn - <a href="https://github.com/mjtamlyn">mjtamlyn</a></li>
|
||||||
|
<li>Richard Wackerbarth - <a href="https://github.com/wackerbarth">wackerbarth</a></li>
|
||||||
|
<li>Johannes Spielmann - <a href="https://github.com/shezi">shezi</a></li>
|
||||||
|
<li>James Cleveland - <a href="https://github.com/radiosilence">radiosilence</a></li>
|
||||||
|
<li>Steve Gregory - <a href="https://github.com/steve-gregory">steve-gregory</a></li>
|
||||||
|
<li>Federico Capoano - <a href="https://github.com/nemesisdesign">nemesisdesign</a></li>
|
||||||
|
<li>Bruno Renié - <a href="https://github.com/brutasse">brutasse</a></li>
|
||||||
|
<li>Kevin Stone - <a href="https://github.com/kevinastone">kevinastone</a></li>
|
||||||
|
<li>Guglielmo Celata - <a href="https://github.com/guglielmo">guglielmo</a></li>
|
||||||
|
<li>Mike Tums - <a href="https://github.com/mktums">mktums</a></li>
|
||||||
|
<li>Michael Elovskikh - <a href="https://github.com/wronglink">wronglink</a></li>
|
||||||
|
<li>Michał Jaworski - <a href="https://github.com/swistakm">swistakm</a></li>
|
||||||
|
<li>Andrea de Marco - <a href="https://github.com/z4r">z4r</a></li>
|
||||||
|
<li>Fernando Rocha - <a href="https://github.com/fernandogrd">fernandogrd</a></li>
|
||||||
|
<li>Xavier Ordoquy - <a href="https://github.com/xordoquy">xordoquy</a></li>
|
||||||
|
<li>Adam Wentz - <a href="https://github.com/floppya">floppya</a></li>
|
||||||
|
<li>Andreas Pelme - <a href="https://github.com/pelme">pelme</a></li>
|
||||||
|
<li>Ryan Detzel - <a href="https://github.com/ryanrdetzel">ryanrdetzel</a></li>
|
||||||
|
<li>Omer Katz - <a href="https://github.com/thedrow">thedrow</a></li>
|
||||||
|
<li>Wiliam Souza - <a href="https://github.com/wiliamsouza">waa</a></li>
|
||||||
|
<li>Jonas Braun - <a href="https://github.com/iekadou">iekadou</a></li>
|
||||||
|
<li>Ian Dash - <a href="https://github.com/bitmonkey">bitmonkey</a></li>
|
||||||
|
<li>Bouke Haarsma - <a href="https://github.com/bouke">bouke</a></li>
|
||||||
|
<li>Pierre Dulac - <a href="https://github.com/dulaccc">dulaccc</a></li>
|
||||||
|
<li>Dave Kuhn - <a href="https://github.com/kuhnza">kuhnza</a></li>
|
||||||
|
<li>Sitong Peng - <a href="https://github.com/stoneg">stoneg</a></li>
|
||||||
|
<li>Victor Shih - <a href="https://github.com/vshih">vshih</a></li>
|
||||||
|
<li>Atle Frenvik Sveen - <a href="https://github.com/atlefren">atlefren</a></li>
|
||||||
|
<li>J Paul Reed - <a href="https://github.com/preed">preed</a></li>
|
||||||
|
<li>Matt Majewski - <a href="https://github.com/forgingdestiny">forgingdestiny</a></li>
|
||||||
|
<li>Jerome Chen - <a href="https://github.com/chenjyw">chenjyw</a></li>
|
||||||
|
<li>Andrew Hughes - <a href="https://github.com/eyepulp">eyepulp</a></li>
|
||||||
|
<li>Daniel Hepper - <a href="https://github.com/dhepper">dhepper</a></li>
|
||||||
|
<li>Hamish Campbell - <a href="https://github.com/hamishcampbell">hamishcampbell</a></li>
|
||||||
|
<li>Marlon Bailey - <a href="https://github.com/avinash240">avinash240</a></li>
|
||||||
|
<li>James Summerfield - <a href="https://github.com/jsummerfield">jsummerfield</a></li>
|
||||||
|
<li>Andy Freeland - <a href="https://github.com/rouge8">rouge8</a></li>
|
||||||
|
<li>Craig de Stigter - <a href="https://github.com/craigds">craigds</a></li>
|
||||||
|
<li>Pablo Recio - <a href="https://github.com/pyriku">pyriku</a></li>
|
||||||
|
<li>Brian Zambrano - <a href="https://github.com/brianz">brianz</a></li>
|
||||||
|
<li>Òscar Vilaplana - <a href="https://github.com/grimborg">grimborg</a></li>
|
||||||
|
<li>Ryan Kaskel - <a href="https://github.com/ryankask">ryankask</a></li>
|
||||||
|
<li>Andy McKay - <a href="https://github.com/andymckay">andymckay</a></li>
|
||||||
|
<li>Matteo Suppo - <a href="https://github.com/matteosuppo">matteosuppo</a></li>
|
||||||
|
<li>Karol Majta - <a href="https://github.com/lolek09">lolek09</a></li>
|
||||||
|
<li>David Jones - <a href="https://github.com/commonorgarden">commonorgarden</a></li>
|
||||||
|
<li>Andrew Tarzwell - <a href="https://github.com/atarzwell">atarzwell</a></li>
|
||||||
|
<li>Michal Dvořák - <a href="https://github.com/mikee2185">mikee2185</a></li>
|
||||||
|
<li>Markus Törnqvist - <a href="https://github.com/mjtorn">mjtorn</a></li>
|
||||||
|
<li>Pascal Borreli - <a href="https://github.com/pborreli">pborreli</a></li>
|
||||||
|
<li>Alex Burgel - <a href="https://github.com/aburgel">aburgel</a></li>
|
||||||
|
<li>David Medina - <a href="https://github.com/copitux">copitux</a></li>
|
||||||
|
<li>Areski Belaid - <a href="https://github.com/areski">areski</a></li>
|
||||||
|
<li>Ethan Freman - <a href="https://github.com/mindlace">mindlace</a></li>
|
||||||
|
<li>David Sanders - <a href="https://github.com/davesque">davesque</a></li>
|
||||||
|
<li>Philip Douglas - <a href="https://github.com/freakydug">freakydug</a></li>
|
||||||
|
<li>Igor Kalat - <a href="https://github.com/trwired">trwired</a></li>
|
||||||
|
<li>Rudolf Olah - <a href="https://github.com/omouse">omouse</a></li>
|
||||||
|
<li>Gertjan Oude Lohuis - <a href="https://github.com/gertjanol">gertjanol</a></li>
|
||||||
|
<li>Matthias Jacob - <a href="https://github.com/cyroxx">cyroxx</a></li>
|
||||||
|
<li>Pavel Zinovkin - <a href="https://github.com/pzinovkin">pzinovkin</a></li>
|
||||||
|
<li>Will Kahn-Greene - <a href="https://github.com/willkg">willkg</a></li>
|
||||||
|
<li>Kevin Brown - <a href="https://github.com/kevin-brown">kevin-brown</a></li>
|
||||||
|
<li>Rodrigo Martell - <a href="https://github.com/coderigo">coderigo</a></li>
|
||||||
|
<li>James Rutherford - <a href="https://github.com/jimr">jimr</a></li>
|
||||||
|
<li>Ricky Rosario - <a href="https://github.com/rlr">rlr</a></li>
|
||||||
|
<li>Veronica Lynn - <a href="https://github.com/kolvia">kolvia</a></li>
|
||||||
|
<li>Dan Stephenson - <a href="https://github.com/etos">etos</a></li>
|
||||||
|
<li>Martin Clement - <a href="https://github.com/martync">martync</a></li>
|
||||||
|
<li>Jeremy Satterfield - <a href="https://github.com/jsatt">jsatt</a></li>
|
||||||
|
<li>Christopher Paolini - <a href="https://github.com/chrispaolini">chrispaolini</a></li>
|
||||||
|
<li>Filipe A Ximenes - <a href="https://github.com/filipeximenes">filipeximenes</a></li>
|
||||||
|
<li>Ramiro Morales - <a href="https://github.com/ramiro">ramiro</a></li>
|
||||||
|
<li>Krzysztof Jurewicz - <a href="https://github.com/krzysiekj">krzysiekj</a></li>
|
||||||
|
<li>Eric Buehl - <a href="https://github.com/ericbuehl">ericbuehl</a></li>
|
||||||
|
<li>Kristian Øllegaard - <a href="https://github.com/kristianoellegaard">kristianoellegaard</a></li>
|
||||||
|
<li>Alexander Akhmetov - <a href="https://github.com/alexander-akhmetov">alexander-akhmetov</a></li>
|
||||||
|
<li>Andrey Antukh - <a href="https://github.com/niwibe">niwibe</a></li>
|
||||||
|
<li>Mathieu Pillard - <a href="https://github.com/diox">diox</a></li>
|
||||||
|
<li>Edmond Wong - <a href="https://github.com/edmondwong">edmondwong</a></li>
|
||||||
|
<li>Ben Reilly - <a href="https://github.com/bwreilly">bwreilly</a></li>
|
||||||
|
<li>Tai Lee - <a href="https://github.com/mrmachine">mrmachine</a></li>
|
||||||
|
<li>Markus Kaiserswerth - <a href="https://github.com/mkai">mkai</a></li>
|
||||||
|
<li>Henry Clifford - <a href="https://github.com/hcliff">hcliff</a></li>
|
||||||
|
<li>Thomas Badaud - <a href="https://github.com/badale">badale</a></li>
|
||||||
|
<li>Colin Huang - <a href="https://github.com/tamakisquare">tamakisquare</a></li>
|
||||||
|
<li>Ross McFarland - <a href="https://github.com/ross">ross</a></li>
|
||||||
|
<li>Jacek Bzdak - <a href="https://github.com/jbzdak">jbzdak</a></li>
|
||||||
|
<li>Alexander Lukanin - <a href="https://github.com/alexanderlukanin13">alexanderlukanin13</a></li>
|
||||||
|
<li>Yamila Moreno - <a href="https://github.com/yamila-moreno">yamila-moreno</a></li>
|
||||||
|
<li>Rob Hudson - <a href="https://github.com/robhudson">robhudson</a></li>
|
||||||
|
<li>Alex Good - <a href="https://github.com/alexjg">alexjg</a></li>
|
||||||
|
</ul>
|
||||||
|
<p>Many thanks to everyone who's contributed to the project.</p>
|
||||||
|
<h2 id="additional-thanks">Additional thanks</h2>
|
||||||
|
<p>The documentation is built with <a href="http://twitter.github.com/bootstrap/">Bootstrap</a> and <a href="http://daringfireball.net/projects/markdown/">Markdown</a>.</p>
|
||||||
|
<p>Project hosting is with <a href="https://github.com/tomchristie/django-rest-framework">GitHub</a>.</p>
|
||||||
|
<p>Continuous integration testing is managed with <a href="https://secure.travis-ci.org/tomchristie/django-rest-framework">Travis CI</a>.</p>
|
||||||
|
<p>The <a href="http://restframework.herokuapp.com/">live sandbox</a> is hosted on <a href="http://www.heroku.com/">Heroku</a>.</p>
|
||||||
|
<p>Various inspiration taken from the <a href="http://rubyonrails.org/">Rails</a>, <a href="https://bitbucket.org/jespern/django-piston">Piston</a>, <a href="https://github.com/toastdriven/django-tastypie">Tastypie</a>, <a href="https://github.com/zacharyvoase/dagny">Dagny</a> and <a href="https://github.com/BertrandBordage/django-viewsets">django-viewsets</a> projects.</p>
|
||||||
|
<p>Development of REST framework 2.0 was sponsored by <a href="http://lab.dabapps.com">DabApps</a>.</p>
|
||||||
|
<h2 id="contact">Contact</h2>
|
||||||
|
<p>For usage questions please see the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">REST framework discussion group</a>.</p>
|
||||||
|
<p>You can also contact <a href="http://twitter.com/_tomchristie">@_tomchristie</a> directly on twitter.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
302
topics/documenting-your-api.html
Normal file
|
@ -0,0 +1,302 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Documenting your API</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Documenting your API">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="documenting-your-api-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 " href="../topics/ajax-csrf-cors.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/settings.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#documenting-your-api">Documenting your API</a></li>
|
||||||
|
<li><a href="#endpoint-documentation">Endpoint documentation</a></li>
|
||||||
|
<li><a href="#self-describing-apis">Self describing APIs</a></li>
|
||||||
|
<li><a href="#the-hypermedia-approach">The hypermedia approach</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="documenting-your-api">Documenting your API</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>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.</p>
|
||||||
|
<p>— Roy Fielding, <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">REST APIs must be hypertext driven</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<p>There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.</p>
|
||||||
|
<h2 id="endpoint-documentation">Endpoint documentation</h2>
|
||||||
|
<p>The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.</p>
|
||||||
|
<hr />
|
||||||
|
<h4 id="django-rest-swagger">Django REST Swagger</h4>
|
||||||
|
<p>Marc Gibbons' <a href="https://github.com/marcgibbons/django-rest-swagger">Django REST Swagger</a> integrates REST framework with the <a href="https://developers.helloreverb.com/swagger/">Swagger</a> API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.</p>
|
||||||
|
<p>The package is fully documented, well supported, and comes highly recommended.</p>
|
||||||
|
<p>Django REST Swagger supports REST framework versions 2.3 and above.</p>
|
||||||
|
<p><img alt="Screenshot - Django REST Swagger" src="../img/django-rest-swagger.png" /></p>
|
||||||
|
<hr />
|
||||||
|
<h4 id="rest-framework-docs">REST Framework Docs</h4>
|
||||||
|
<p>The <a href="https://github.com/marcgibbons/django-rest-framework-docs">REST Framework Docs</a> package is an earlier project, also by Marc Gibbons, that offers clean, simple autogenerated documentation for your API.</p>
|
||||||
|
<p><img alt="Screenshot - REST Framework Docs" src="../img/rest-framework-docs.png" /></p>
|
||||||
|
<hr />
|
||||||
|
<h4 id="apiary">Apiary</h4>
|
||||||
|
<p>There are various other online tools and services for providing API documentation. One notable service is <a href="http://apiary.io/">Apiary</a>. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.</p>
|
||||||
|
<p><img alt="Screenshot - Apiary" src="../img/apiary.png" /></p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="self-describing-apis">Self describing APIs</h2>
|
||||||
|
<p>The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.</p>
|
||||||
|
<p><img alt="Screenshot - Self describing API" src="../img/self-describing.png" /></p>
|
||||||
|
<hr />
|
||||||
|
<h4 id="setting-the-title">Setting the title</h4>
|
||||||
|
<p>The title that is used in the browsable API is generated from the view class name or function name. Any trailing <code>View</code> or <code>ViewSet</code> suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.</p>
|
||||||
|
<p>For example, the view <code>UserListView</code>, will be named <code>User List</code> when presented in the browsable API.</p>
|
||||||
|
<p>When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set <code>UserViewSet</code> will generate views named <code>User List</code> and <code>User Instance</code>. </p>
|
||||||
|
<h4 id="setting-the-description">Setting the description</h4>
|
||||||
|
<p>The description in the browsable API is generated from the docstring of the view or viewset.</p>
|
||||||
|
<p>If the python <code>markdown</code> library is installed, then <a href="http://daringfireball.net/projects/markdown/">markdown syntax</a> may be used in the docstring, and will be converted to HTML in the browsable API. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class AccountListView(views.APIView):
|
||||||
|
"""
|
||||||
|
Returns a list of all **active** accounts in the system.
|
||||||
|
|
||||||
|
For more details on how accounts are activated please [see here][ref].
|
||||||
|
|
||||||
|
[ref]: http://example.com/activating-accounts
|
||||||
|
"""
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.</p>
|
||||||
|
<h4 id="the-options-method">The <code>OPTIONS</code> method</h4>
|
||||||
|
<p>REST framework APIs also support programmatically accessible descriptions, using the <code>OPTIONS</code> HTTP method. A view will respond to an <code>OPTIONS</code> request with metadata including the name, description, and the various media types it accepts and responds with.</p>
|
||||||
|
<p>When using the generic views, any <code>OPTIONS</code> requests will additionally respond with metadata regarding any <code>POST</code> or <code>PUT</code> actions available, describing which fields are on the serializer.</p>
|
||||||
|
<p>You can modify the response behavior to <code>OPTIONS</code> requests by overriding the <code>metadata</code> view method. For example:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def metadata(self, request):
|
||||||
|
"""
|
||||||
|
Don't include the view description in OPTIONS responses.
|
||||||
|
"""
|
||||||
|
data = super(ExampleView, self).metadata(request)
|
||||||
|
data.pop('description')
|
||||||
|
return data
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h2 id="the-hypermedia-approach">The hypermedia approach</h2>
|
||||||
|
<p>To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.</p>
|
||||||
|
<p>In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the <em>media types</em> that are used. The available actions take may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.</p>
|
||||||
|
<p>To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The <a href="rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a> section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
771
topics/release-notes.html
Normal file
|
@ -0,0 +1,771 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Release Notes</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Release Notes">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="release-notes-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 " href="../topics/credits.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/2.3-announcement.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#release-notes">Release Notes</a></li>
|
||||||
|
<li><a href="#versioning">Versioning</a></li>
|
||||||
|
<li><a href="#deprecation-policy">Deprecation policy</a></li>
|
||||||
|
<li><a href="#upgrading">Upgrading</a></li>
|
||||||
|
<li><a href="#23x-series">2.3.x series</a></li>
|
||||||
|
<li><a href="#22x-series">2.2.x series</a></li>
|
||||||
|
<li><a href="#21x-series">2.1.x series</a></li>
|
||||||
|
<li><a href="#20x-series">2.0.x series</a></li>
|
||||||
|
<li><a href="#04x-series">0.4.x series</a></li>
|
||||||
|
<li><a href="#03x-series">0.3.x series</a></li>
|
||||||
|
<li><a href="#02x-series">0.2.x series</a></li>
|
||||||
|
<li><a href="#01x-series">0.1.x series</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="release-notes">Release Notes</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>Release Early, Release Often</p>
|
||||||
|
<p>— Eric S. Raymond, <a href="http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html">The Cathedral and the Bazaar</a>.</p>
|
||||||
|
</blockquote>
|
||||||
|
<h2 id="versioning">Versioning</h2>
|
||||||
|
<p>Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.</p>
|
||||||
|
<p>Medium version numbers (0.x.0) may include API changes, in line with the <a href="#deprecation-policy">deprecation policy</a>. You should read the release notes carefully before upgrading between medium point releases.</p>
|
||||||
|
<p>Major version numbers (x.0.0) are reserved for substantial project milestones. No major point releases are currently planned.</p>
|
||||||
|
<h2 id="deprecation-policy">Deprecation policy</h2>
|
||||||
|
<p>REST framework releases follow a formal deprecation policy, which is in line with <a href="https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy">Django's deprecation policy</a>.</p>
|
||||||
|
<p>The timeline for deprecation of a feature present in version 1.0 would work as follows:</p>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<p>Version 1.1 would remain <strong>fully backwards compatible</strong> with 1.0, but would raise <code>PendingDeprecationWarning</code> warnings if you use the feature that are due to be deprecated. These warnings are <strong>silent by default</strong>, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using <code>python -Wd manage.py test</code>, you'll be warned of any API changes you need to make.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>Version 1.2 would escalate these warnings to <code>DeprecationWarning</code>, which is loud by default.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>Version 1.3 would remove the deprecated bits of API entirely.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p>Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.</p>
|
||||||
|
<h2 id="upgrading">Upgrading</h2>
|
||||||
|
<p>To upgrade Django REST framework to the latest version, use pip:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>pip install -U djangorestframework
|
||||||
|
</code></pre>
|
||||||
|
<p>You can determine your currently installed version using <code>pip freeze</code>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>pip freeze | grep djangorestframework
|
||||||
|
</code></pre>
|
||||||
|
<hr />
|
||||||
|
<h2 id="23x-series">2.3.x series</h2>
|
||||||
|
<h3 id="239">2.3.9</h3>
|
||||||
|
<p><strong>Date</strong>: 15th November 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Fix Django 1.6 exception API compatibility issue caused by <code>ValidationError</code>.</li>
|
||||||
|
<li>Include errors in HTML forms in browsable API.</li>
|
||||||
|
<li>Added JSON renderer support for numpy scalars.</li>
|
||||||
|
<li>Added <code>transform_<fieldname></code> hooks on serializers for easily modifying field output.</li>
|
||||||
|
<li>Added <code>get_context</code> hook in <code>BrowsableAPIRenderer</code>.</li>
|
||||||
|
<li>Allow serializers to be passed <code>files</code> but no <code>data</code>.</li>
|
||||||
|
<li><code>HTMLFormRenderer</code> now renders serializers directly to HTML without needing to create an intermediate form object.</li>
|
||||||
|
<li>Added <code>get_filter_backends</code> hook.</li>
|
||||||
|
<li>Added queryset aggregates to allowed fields in <code>OrderingFilter</code>.</li>
|
||||||
|
<li>Bugfix: Fix decimal suppoprt with <code>YAMLRenderer</code>.</li>
|
||||||
|
<li>Bugfix: Fix submission of unicode in browsable API through raw data form.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="238">2.3.8</h3>
|
||||||
|
<p><strong>Date</strong>: 11th September 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Added <code>DjangoObjectPermissions</code>, and <code>DjangoObjectPermissionsFilter</code>.</li>
|
||||||
|
<li>Support customizable exception handling, using the <code>EXCEPTION_HANDLER</code> setting.</li>
|
||||||
|
<li>Support customizable view name and description functions, using the <code>VIEW_NAME_FUNCTION</code> and <code>VIEW_DESCRIPTION_FUNCTION</code> settings.</li>
|
||||||
|
<li>Added <code>MAX_PAGINATE_BY</code> setting and <code>max_paginate_by</code> generic view attribute.</li>
|
||||||
|
<li>Added <code>cache</code> attribute to throttles to allow overriding of default cache.</li>
|
||||||
|
<li>'Raw data' tab in browsable API now contains pre-populated data.</li>
|
||||||
|
<li>'Raw data' and 'HTML form' tab preference in browseable API now saved between page views.</li>
|
||||||
|
<li>Bugfix: <code>required=True</code> argument fixed for boolean serializer fields.</li>
|
||||||
|
<li>Bugfix: <code>client.force_authenticate(None)</code> should also clear session info if it exists.</li>
|
||||||
|
<li>Bugfix: Client sending empty string instead of file now clears <code>FileField</code>.</li>
|
||||||
|
<li>Bugfix: Empty values on ChoiceFields with <code>required=False</code> now consistently return <code>None</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="237">2.3.7</h3>
|
||||||
|
<p><strong>Date</strong>: 16th August 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Added <code>APITestClient</code>, <code>APIRequestFactory</code> and <code>APITestCase</code> etc...</li>
|
||||||
|
<li>Refactor <code>SessionAuthentication</code> to allow esier override for CSRF exemption.</li>
|
||||||
|
<li>Remove 'Hold down "Control" message from help_text' widget messaging when not appropriate.</li>
|
||||||
|
<li>Added admin configuration for auth tokens.</li>
|
||||||
|
<li>Bugfix: <code>AnonRateThrottle</code> fixed to not throttle authenticated users.</li>
|
||||||
|
<li>Bugfix: Don't set <code>X-Throttle-Wait-Seconds</code> when throttle does not have <code>wait</code> value.</li>
|
||||||
|
<li>Bugfix: Fixed <code>PATCH</code> button title in browsable API.</li>
|
||||||
|
<li>Bugfix: Fix issue with OAuth2 provider naive datetimes.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="236">2.3.6</h3>
|
||||||
|
<p><strong>Date</strong>: 27th June 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Added <code>trailing_slash</code> option to routers.</li>
|
||||||
|
<li>Include support for <code>HttpStreamingResponse</code>.</li>
|
||||||
|
<li>Support wider range of default serializer validation when used with custom model fields.</li>
|
||||||
|
<li>UTF-8 Support for browsable API descriptions. </li>
|
||||||
|
<li>OAuth2 provider uses timezone aware datetimes when supported.</li>
|
||||||
|
<li>Bugfix: Return error correctly when OAuth non-existent consumer occurs. </li>
|
||||||
|
<li>Bugfix: Allow <code>FileUploadParser</code> to correctly filename if provided as URL kwarg.</li>
|
||||||
|
<li>Bugfix: Fix <code>ScopedRateThrottle</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="235">2.3.5</h3>
|
||||||
|
<p><strong>Date</strong>: 3rd June 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Added <code>get_url</code> hook to <code>HyperlinkedIdentityField</code>.</li>
|
||||||
|
<li>Serializer field <code>default</code> argument may be a callable.</li>
|
||||||
|
<li><code>@action</code> decorator now accepts a <code>methods</code> argument.</li>
|
||||||
|
<li>Bugfix: <code>request.user</code> should be still be accessible in renderer context if authentication fails.</li>
|
||||||
|
<li>Bugfix: The <code>lookup_field</code> option on <code>HyperlinkedIdentityField</code> should apply by default to the url field on the serializer.</li>
|
||||||
|
<li>Bugfix: <code>HyperlinkedIdentityField</code> should continue to support <code>pk_url_kwarg</code>, <code>slug_url_kwarg</code>, <code>slug_field</code>, in a pending deprecation state.</li>
|
||||||
|
<li>Bugfix: Ensure we always return 404 instead of 500 if a lookup field cannot be converted to the correct lookup type. (Eg non-numeric <code>AutoInteger</code> pk lookup)</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="234">2.3.4</h3>
|
||||||
|
<p><strong>Date</strong>: 24th May 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Serializer fields now support <code>label</code> and <code>help_text</code>.</li>
|
||||||
|
<li>Added <code>UnicodeJSONRenderer</code>.</li>
|
||||||
|
<li><code>OPTIONS</code> requests now return metadata about fields for <code>POST</code> and <code>PUT</code> requests.</li>
|
||||||
|
<li>Bugfix: <code>charset</code> now properly included in <code>Content-Type</code> of responses.</li>
|
||||||
|
<li>Bugfix: Blank choice now added in browsable API on nullable relationships.</li>
|
||||||
|
<li>Bugfix: Many to many relationships with <code>through</code> tables are now read-only.</li>
|
||||||
|
<li>Bugfix: Serializer fields now respect model field args such as <code>max_length</code>.</li>
|
||||||
|
<li>Bugfix: SlugField now performs slug validation.</li>
|
||||||
|
<li>Bugfix: Lazy-translatable strings now properly serialized.</li>
|
||||||
|
<li>Bugfix: Browsable API now supports bootswatch styles properly.</li>
|
||||||
|
<li>Bugfix: HyperlinkedIdentityField now uses <code>lookup_field</code> kwarg.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note</strong>: Responses now correctly include an appropriate charset on the <code>Content-Type</code> header. For example: <code>application/json; charset=utf-8</code>. If you have tests that check the content type of responses, you may need to update these accordingly.</p>
|
||||||
|
<h3 id="233">2.3.3</h3>
|
||||||
|
<p><strong>Date</strong>: 16th May 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Added SearchFilter</li>
|
||||||
|
<li>Added OrderingFilter</li>
|
||||||
|
<li>Added GenericViewSet</li>
|
||||||
|
<li>Bugfix: Multiple <code>@action</code> and <code>@link</code> methods now allowed on viewsets. </li>
|
||||||
|
<li>Bugfix: Fix API Root view issue with DjangoModelPermissions</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="232">2.3.2</h3>
|
||||||
|
<p><strong>Date</strong>: 8th May 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Fix <code>TIME_FORMAT</code>, <code>DATETIME_FORMAT</code> and <code>DATE_FORMAT</code> settings.</li>
|
||||||
|
<li>Bugfix: Fix <code>DjangoFilterBackend</code> issue, failing when used on view with queryset attribute.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="231">2.3.1</h3>
|
||||||
|
<p><strong>Date</strong>: 7th May 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Fix breadcrumb rendering issue.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="230">2.3.0</h3>
|
||||||
|
<p><strong>Date</strong>: 7th May 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>ViewSets and Routers.</li>
|
||||||
|
<li>ModelSerializers support reverse relations in 'fields' option.</li>
|
||||||
|
<li>HyperLinkedModelSerializers support 'id' field in 'fields' option.</li>
|
||||||
|
<li>Cleaner generic views.</li>
|
||||||
|
<li>Support for multiple filter classes.</li>
|
||||||
|
<li>FileUploadParser support for raw file uploads.</li>
|
||||||
|
<li>DecimalField support.</li>
|
||||||
|
<li>Made Login template easier to restyle.</li>
|
||||||
|
<li>Bugfix: Fix issue with depth>1 on ModelSerializer.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note</strong>: See the <a href="2.3-announcement.html">2.3 announcement</a> for full details.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="22x-series">2.2.x series</h2>
|
||||||
|
<h3 id="227">2.2.7</h3>
|
||||||
|
<p><strong>Date</strong>: 17th April 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Loud failure when view does not return a <code>Response</code> or <code>HttpResponse</code>.</li>
|
||||||
|
<li>Bugfix: Fix for Django 1.3 compatibility.</li>
|
||||||
|
<li>Bugfix: Allow overridden <code>get_object()</code> to work correctly.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="226">2.2.6</h3>
|
||||||
|
<p><strong>Date</strong>: 4th April 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>OAuth2 authentication no longer requires unnecessary URL parameters in addition to the token.</li>
|
||||||
|
<li>URL hyperlinking in browsable API now handles more cases correctly.</li>
|
||||||
|
<li>Long HTTP headers in browsable API are broken in multiple lines when possible.</li>
|
||||||
|
<li>Bugfix: Fix regression with DjangoFilterBackend not worthing correctly with single object views.</li>
|
||||||
|
<li>Bugfix: OAuth should fail hard when invalid token used.</li>
|
||||||
|
<li>Bugfix: Fix serializer potentially returning <code>None</code> object for models that define <code>__bool__</code> or <code>__len__</code>. </li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="225">2.2.5</h3>
|
||||||
|
<p><strong>Date</strong>: 26th March 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Serializer support for bulk create and bulk update operations.</li>
|
||||||
|
<li>Regression fix: Date and time fields return date/time objects by default. Fixes regressions caused by 2.2.2. See <a href="https://github.com/tomchristie/django-rest-framework/pull/743">#743</a> for more details.</li>
|
||||||
|
<li>Bugfix: Fix 500 error is OAuth not attempted with OAuthAuthentication class installed.</li>
|
||||||
|
<li><code>Serializer.save()</code> now supports arbitrary keyword args which are passed through to the object <code>.save()</code> method. Mixins use <code>force_insert</code> and <code>force_update</code> where appropriate, resulting in one less database query.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="224">2.2.4</h3>
|
||||||
|
<p><strong>Date</strong>: 13th March 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>OAuth 2 support.</li>
|
||||||
|
<li>OAuth 1.0a support.</li>
|
||||||
|
<li>Support X-HTTP-Method-Override header.</li>
|
||||||
|
<li>Filtering backends are now applied to the querysets for object lookups as well as lists. (Eg you can use a filtering backend to control which objects should 404)</li>
|
||||||
|
<li>Deal with error data nicely when deserializing lists of objects.</li>
|
||||||
|
<li>Extra override hook to configure <code>DjangoModelPermissions</code> for unauthenticated users.</li>
|
||||||
|
<li>Bugfix: Fix regression which caused extra database query on paginated list views.</li>
|
||||||
|
<li>Bugfix: Fix pk relationship bug for some types of 1-to-1 relations.</li>
|
||||||
|
<li>Bugfix: Workaround for Django bug causing case where <code>Authtoken</code> could be registered for cascade delete from <code>User</code> even if not installed.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="223">2.2.3</h3>
|
||||||
|
<p><strong>Date</strong>: 7th March 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Fix None values for for <code>DateField</code>, <code>DateTimeField</code> and <code>TimeField</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="222">2.2.2</h3>
|
||||||
|
<p><strong>Date</strong>: 6th March 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Support for custom input and output formats for <code>DateField</code>, <code>DateTimeField</code> and <code>TimeField</code>.</li>
|
||||||
|
<li>Cleanup: Request authentication is no longer lazily evaluated, instead authentication is always run, which results in more consistent, obvious behavior. Eg. Supplying bad auth credentials will now always return an error response, even if no permissions are set on the view.</li>
|
||||||
|
<li>Bugfix for serializer data being uncacheable with pickle protocol 0.</li>
|
||||||
|
<li>Bugfixes for model field validation edge-cases.</li>
|
||||||
|
<li>Bugfix for authtoken migration while using a custom user model and south.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="221">2.2.1</h3>
|
||||||
|
<p><strong>Date</strong>: 22nd Feb 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Security fix: Use <code>defusedxml</code> package to address XML parsing vulnerabilities.</li>
|
||||||
|
<li>Raw data tab added to browsable API. (Eg. Allow for JSON input.)</li>
|
||||||
|
<li>Added TimeField.</li>
|
||||||
|
<li>Serializer fields can be mapped to any method that takes no args, or only takes kwargs which have defaults.</li>
|
||||||
|
<li>Unicode support for view names/descriptions in browsable API.</li>
|
||||||
|
<li>Bugfix: request.DATA should return an empty <code>QueryDict</code> with no data, not <code>None</code>.</li>
|
||||||
|
<li>Bugfix: Remove unneeded field validation, which caused extra queries.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Security note</strong>: Following the <a href="http://blog.python.org/2013/02/announcing-defusedxml-fixes-for-xml.html">disclosure of security vulnerabilities</a> in Python's XML parsing libraries, use of the <code>XMLParser</code> class now requires the <code>defusedxml</code> package to be installed.</p>
|
||||||
|
<p>The security vulnerabilities only affect APIs which use the <code>XMLParser</code> class, by enabling it in any views, or by having it set in the <code>DEFAULT_PARSER_CLASSES</code> setting. Note that the <code>XMLParser</code> class is not enabled by default, so this change should affect a minority of users.</p>
|
||||||
|
<h3 id="220">2.2.0</h3>
|
||||||
|
<p><strong>Date</strong>: 13th Feb 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Python 3 support.</li>
|
||||||
|
<li>Added a <code>post_save()</code> hook to the generic views.</li>
|
||||||
|
<li>Allow serializers to handle dicts as well as objects.</li>
|
||||||
|
<li>Deprecate <code>ManyRelatedField()</code> syntax in favor of <code>RelatedField(many=True)</code></li>
|
||||||
|
<li>Deprecate <code>null=True</code> on relations in favor of <code>required=False</code>.</li>
|
||||||
|
<li>Deprecate <code>blank=True</code> on CharFields, just use <code>required=False</code>.</li>
|
||||||
|
<li>Deprecate optional <code>obj</code> argument in permissions checks in favor of <code>has_object_permission</code>.</li>
|
||||||
|
<li>Deprecate implicit hyperlinked relations behavior.</li>
|
||||||
|
<li>Bugfix: Fix broken DjangoModelPermissions.</li>
|
||||||
|
<li>Bugfix: Allow serializer output to be cached.</li>
|
||||||
|
<li>Bugfix: Fix styling on browsable API login.</li>
|
||||||
|
<li>Bugfix: Fix issue with deserializing empty to-many relations.</li>
|
||||||
|
<li>Bugfix: Ensure model field validation is still applied for ModelSerializer subclasses with an custom <code>.restore_object()</code> method.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note</strong>: See the <a href="2.2-announcement.html">2.2 announcement</a> for full details.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="21x-series">2.1.x series</h2>
|
||||||
|
<h3 id="2117">2.1.17</h3>
|
||||||
|
<p><strong>Date</strong>: 26th Jan 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.</li>
|
||||||
|
<li>Support json encoding of timedelta objects.</li>
|
||||||
|
<li><code>format_suffix_patterns()</code> now supports <code>include</code> style URL patterns.</li>
|
||||||
|
<li>Bugfix: Fix issues with custom pagination serializers.</li>
|
||||||
|
<li>Bugfix: Nested serializers now accept <code>source='*'</code> argument.</li>
|
||||||
|
<li>Bugfix: Return proper validation errors when incorrect types supplied for relational fields.</li>
|
||||||
|
<li>Bugfix: Support nullable FKs with <code>SlugRelatedField</code>.</li>
|
||||||
|
<li>Bugfix: Don't call custom validation methods if the field has an error.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note</strong>: If the primary authentication class is <code>TokenAuthentication</code> or <code>BasicAuthentication</code>, a view will now correctly return 401 responses to unauthenticated access, with an appropriate <code>WWW-Authenticate</code> header, instead of 403 responses.</p>
|
||||||
|
<h3 id="2116">2.1.16</h3>
|
||||||
|
<p><strong>Date</strong>: 14th Jan 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Deprecate <code>django.utils.simplejson</code> in favor of Python 2.6's built-in json module.</li>
|
||||||
|
<li>Bugfix: <code>auto_now</code>, <code>auto_now_add</code> and other <code>editable=False</code> fields now default to read-only.</li>
|
||||||
|
<li>Bugfix: PK fields now only default to read-only if they are an AutoField or if <code>editable=False</code>.</li>
|
||||||
|
<li>Bugfix: Validation errors instead of exceptions when serializers receive incorrect types.</li>
|
||||||
|
<li>Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.</li>
|
||||||
|
<li>Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note</strong>: Prior to 2.1.16, The Decimals would render in JSON using floating point if <code>simplejson</code> was installed, but otherwise render using string notation. Now that use of <code>simplejson</code> has been deprecated, Decimals will consistently render using string notation. See <a href="https://github.com/tomchristie/django-rest-framework/issues/582">#582</a> for more details.</p>
|
||||||
|
<h3 id="2115">2.1.15</h3>
|
||||||
|
<p><strong>Date</strong>: 3rd Jan 2013</p>
|
||||||
|
<ul>
|
||||||
|
<li>Added <code>PATCH</code> support.</li>
|
||||||
|
<li>Added <code>RetrieveUpdateAPIView</code>.</li>
|
||||||
|
<li>Remove unused internal <code>save_m2m</code> flag on <code>ModelSerializer.save()</code>.</li>
|
||||||
|
<li>Tweak behavior of hyperlinked fields with an explicit format suffix.</li>
|
||||||
|
<li>Relation changes are now persisted in <code>.save()</code> instead of in <code>.restore_object()</code>.</li>
|
||||||
|
<li>Bugfix: Fix issue with FileField raising exception instead of validation error when files=None.</li>
|
||||||
|
<li>Bugfix: Partial updates should not set default values if field is not included.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="2114">2.1.14</h3>
|
||||||
|
<p><strong>Date</strong>: 31st Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: ModelSerializers now include reverse FK fields on creation.</li>
|
||||||
|
<li>Bugfix: Model fields with <code>blank=True</code> are now <code>required=False</code> by default.</li>
|
||||||
|
<li>Bugfix: Nested serializers now support nullable relationships.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Note</strong>: From 2.1.14 onwards, relational fields move out of the <code>fields.py</code> module and into the new <code>relations.py</code> module, in order to separate them from regular data type fields, such as <code>CharField</code> and <code>IntegerField</code>.</p>
|
||||||
|
<p>This change will not affect user code, so long as it's following the recommended import style of <code>from rest_framework import serializers</code> and referring to fields using the style <code>serializers.PrimaryKeyRelatedField</code>.</p>
|
||||||
|
<h3 id="2113">2.1.13</h3>
|
||||||
|
<p><strong>Date</strong>: 28th Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Support configurable <code>STATICFILES_STORAGE</code> storage.</li>
|
||||||
|
<li>Bugfix: Related fields now respect the required flag, and may be required=False.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="2112">2.1.12</h3>
|
||||||
|
<p><strong>Date</strong>: 21st Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Fix bug that could occur using ChoiceField.</li>
|
||||||
|
<li>Bugfix: Fix exception in browsable API on DELETE.</li>
|
||||||
|
<li>Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="2111">2.1.11</h3>
|
||||||
|
<p><strong>Date</strong>: 17th Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Fix issue with M2M fields in browsable API.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="2110">2.1.10</h3>
|
||||||
|
<p><strong>Date</strong>: 17th Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Ensure read-only fields don't have model validation applied.</li>
|
||||||
|
<li>Bugfix: Fix hyperlinked fields in paginated results.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="219">2.1.9</h3>
|
||||||
|
<p><strong>Date</strong>: 11th Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Fix broken nested serialization.</li>
|
||||||
|
<li>Bugfix: Fix <code>Meta.fields</code> only working as tuple not as list.</li>
|
||||||
|
<li>Bugfix: Edge case if unnecessarily specifying <code>required=False</code> on read only field.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="218">2.1.8</h3>
|
||||||
|
<p><strong>Date</strong>: 8th Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Fix for creating nullable Foreign Keys with <code>''</code> as well as <code>None</code>.</li>
|
||||||
|
<li>Added <code>null=<bool></code> related field option.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="217">2.1.7</h3>
|
||||||
|
<p><strong>Date</strong>: 7th Dec 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Serializers now properly support nullable Foreign Keys.</li>
|
||||||
|
<li>Serializer validation now includes model field validation, such as uniqueness constraints.</li>
|
||||||
|
<li>Support 'true' and 'false' string values for BooleanField.</li>
|
||||||
|
<li>Added pickle support for serialized data.</li>
|
||||||
|
<li>Support <code>source='dotted.notation'</code> style for nested serializers.</li>
|
||||||
|
<li>Make <code>Request.user</code> settable.</li>
|
||||||
|
<li>Bugfix: Fix <code>RegexField</code> to work with <code>BrowsableAPIRenderer</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="216">2.1.6</h3>
|
||||||
|
<p><strong>Date</strong>: 23rd Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Unfix DjangoModelPermissions. (I am a doofus.)</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="215">2.1.5</h3>
|
||||||
|
<p><strong>Date</strong>: 23rd Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfix: Fix DjangoModelPermissions.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="214">2.1.4</h3>
|
||||||
|
<p><strong>Date</strong>: 22nd Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Support for partial updates with serializers.</li>
|
||||||
|
<li>Added <code>RegexField</code>.</li>
|
||||||
|
<li>Added <code>SerializerMethodField</code>.</li>
|
||||||
|
<li>Serializer performance improvements.</li>
|
||||||
|
<li>Added <code>obtain_token_view</code> to get tokens when using <code>TokenAuthentication</code>.</li>
|
||||||
|
<li>Bugfix: Django 1.5 configurable user support for <code>TokenAuthentication</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="213">2.1.3</h3>
|
||||||
|
<p><strong>Date</strong>: 16th Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Added <code>FileField</code> and <code>ImageField</code>. For use with <code>MultiPartParser</code>.</li>
|
||||||
|
<li>Added <code>URLField</code> and <code>SlugField</code>.</li>
|
||||||
|
<li>Support for <code>read_only_fields</code> on <code>ModelSerializer</code> classes.</li>
|
||||||
|
<li>Support for clients overriding the pagination page sizes. Use the <code>PAGINATE_BY_PARAM</code> setting or set the <code>paginate_by_param</code> attribute on a generic view.</li>
|
||||||
|
<li>201 Responses now return a 'Location' header.</li>
|
||||||
|
<li>Bugfix: Serializer fields now respect <code>max_length</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="212">2.1.2</h3>
|
||||||
|
<p><strong>Date</strong>: 9th Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Filtering support.</strong></li>
|
||||||
|
<li>Bugfix: Support creation of objects with reverse M2M relations.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="211">2.1.1</h3>
|
||||||
|
<p><strong>Date</strong>: 7th Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Support use of HTML exception templates. Eg. <code>403.html</code></li>
|
||||||
|
<li>Hyperlinked fields take optional <code>slug_field</code>, <code>slug_url_kwarg</code> and <code>pk_url_kwarg</code> arguments.</li>
|
||||||
|
<li>Bugfix: Deal with optional trailing slashes properly when generating breadcrumbs.</li>
|
||||||
|
<li>Bugfix: Make textareas same width as other fields in browsable API.</li>
|
||||||
|
<li>Private API change: <code>.get_serializer</code> now uses same <code>instance</code> and <code>data</code> ordering as serializer initialization.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="210">2.1.0</h3>
|
||||||
|
<p><strong>Date</strong>: 5th Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Serializer <code>instance</code> and <code>data</code> keyword args have their position swapped.</strong></li>
|
||||||
|
<li><code>queryset</code> argument is now optional on writable model fields.</li>
|
||||||
|
<li>Hyperlinked related fields optionally take <code>slug_field</code> and <code>slug_url_kwarg</code> arguments.</li>
|
||||||
|
<li>Support Django's cache framework.</li>
|
||||||
|
<li>Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)</li>
|
||||||
|
<li>Bugfix: Support choice field in Browsable API.</li>
|
||||||
|
<li>Bugfix: Related fields with <code>read_only=True</code> do not require a <code>queryset</code> argument.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>API-incompatible changes</strong>: Please read <a href="https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion">this thread</a> regarding the <code>instance</code> and <code>data</code> keyword args before updating to 2.1.0.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="20x-series">2.0.x series</h2>
|
||||||
|
<h3 id="202">2.0.2</h3>
|
||||||
|
<p><strong>Date</strong>: 2nd Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Fix issues with pk related fields in the browsable API.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="201">2.0.1</h3>
|
||||||
|
<p><strong>Date</strong>: 1st Nov 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li>Add support for relational fields in the browsable API.</li>
|
||||||
|
<li>Added SlugRelatedField and ManySlugRelatedField.</li>
|
||||||
|
<li>If PUT creates an instance return '201 Created', instead of '200 OK'.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="200">2.0.0</h3>
|
||||||
|
<p><strong>Date</strong>: 30th Oct 2012</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Fix all of the things.</strong> (Well, almost.)</li>
|
||||||
|
<li>For more information please see the <a href="rest-framework-2-announcement.html">2.0 announcement</a>.</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h2 id="04x-series">0.4.x series</h2>
|
||||||
|
<h3 id="040">0.4.0</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Supports Django 1.5.</li>
|
||||||
|
<li>Fixes issues with 'HEAD' method.</li>
|
||||||
|
<li>Allow views to specify template used by TemplateRenderer</li>
|
||||||
|
<li>More consistent error responses</li>
|
||||||
|
<li>Some serializer fixes</li>
|
||||||
|
<li>Fix internet explorer ajax behavior</li>
|
||||||
|
<li>Minor xml and yaml fixes</li>
|
||||||
|
<li>Improve setup (e.g. use staticfiles, not the defunct ADMIN_MEDIA_PREFIX)</li>
|
||||||
|
<li>Sensible absolute URL generation, not using hacky set_script_prefix</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h2 id="03x-series">0.3.x series</h2>
|
||||||
|
<h3 id="033">0.3.3</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Added DjangoModelPermissions class to support <code>django.contrib.auth</code> style permissions.</li>
|
||||||
|
<li>Use <code>staticfiles</code> for css files.</li>
|
||||||
|
<li>Easier to override. Won't conflict with customized admin styles (e.g. grappelli)</li>
|
||||||
|
<li>Templates are now nicely namespaced.</li>
|
||||||
|
<li>Allows easier overriding.</li>
|
||||||
|
<li>Drop implied 'pk' filter if last arg in urlconf is unnamed.</li>
|
||||||
|
<li>Too magical. Explicit is better than implicit.</li>
|
||||||
|
<li>Saner template variable auto-escaping.</li>
|
||||||
|
<li>Tidier setup.py</li>
|
||||||
|
<li>Updated for URLObject 2.0</li>
|
||||||
|
<li>Bugfixes:</li>
|
||||||
|
<li>Bug with PerUserThrottling when user contains unicode chars.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="032">0.3.2</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Bugfixes:</li>
|
||||||
|
<li>Fix 403 for POST and PUT from the UI with UserLoggedInAuthentication (#115)</li>
|
||||||
|
<li>serialize_model method in serializer.py may cause wrong value (#73)</li>
|
||||||
|
<li>Fix Error when clicking OPTIONS button (#146)</li>
|
||||||
|
<li>And many other fixes</li>
|
||||||
|
<li>Remove short status codes</li>
|
||||||
|
<li>Zen of Python: "There should be one-- and preferably only one --obvious way to do it."</li>
|
||||||
|
<li>get_name, get_description become methods on the view - makes them overridable.</li>
|
||||||
|
<li>Improved model mixin API - Hooks for build_query, get_instance_data, get_model, get_queryset, get_ordering</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="031">0.3.1</h3>
|
||||||
|
<ul>
|
||||||
|
<li>[not documented]</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="030">0.3.0</h3>
|
||||||
|
<ul>
|
||||||
|
<li>JSONP Support</li>
|
||||||
|
<li>Bugfixes, including support for latest markdown release</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h2 id="02x-series">0.2.x series</h2>
|
||||||
|
<h3 id="024">0.2.4</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Fix broken IsAdminUser permission.</li>
|
||||||
|
<li>OPTIONS support.</li>
|
||||||
|
<li>XMLParser.</li>
|
||||||
|
<li>Drop mentions of Blog, BitBucket.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="023">0.2.3</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Fix some throttling bugs.</li>
|
||||||
|
<li><code>X-Throttle</code> header on throttling.</li>
|
||||||
|
<li>Support for nesting resources on related models.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="022">0.2.2</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Throttling support complete.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="021">0.2.1</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Couple of simple bugfixes over 0.2.0</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="020">0.2.0</h3>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<p>Big refactoring changes since 0.1.0, ask on the discussion group if anything isn't clear.
|
||||||
|
The public API has been massively cleaned up. Expect it to be fairly stable from here on in.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p><code>Resource</code> becomes decoupled into <code>View</code> and <code>Resource</code>, your views should now inherit from <code>View</code>, not <code>Resource</code>.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>The handler functions on views <code>.get() .put() .post()</code> etc, no longer have the <code>content</code> and <code>auth</code> args.
|
||||||
|
Use <code>self.CONTENT</code> inside a view to access the deserialized, validated content.
|
||||||
|
Use <code>self.user</code> inside a view to access the authenticated user.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p><code>allowed_methods</code> and <code>anon_allowed_methods</code> are now defunct. if a method is defined, it's available.
|
||||||
|
The <code>permissions</code> attribute on a <code>View</code> is now used to provide generic permissions checking.
|
||||||
|
Use permission classes such as <code>FullAnonAccess</code>, <code>IsAuthenticated</code> or <code>IsUserOrIsAnonReadOnly</code> to set the permissions.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>The <code>authenticators</code> class becomes <code>authentication</code>. Class names change to <code>Authentication</code>.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>The <code>emitters</code> class becomes <code>renderers</code>. Class names change to <code>Renderers</code>.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p><code>ResponseException</code> becomes <code>ErrorResponse</code>.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<p>The mixin classes have been nicely refactored, the basic mixins are now <code>RequestMixin</code>, <code>ResponseMixin</code>, <code>AuthMixin</code>, and <code>ResourceMixin</code>
|
||||||
|
You can reuse these mixin classes individually without using the <code>View</code> class.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<hr />
|
||||||
|
<h2 id="01x-series">0.1.x series</h2>
|
||||||
|
<h3 id="011">0.1.1</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Final build before pulling in all the refactoring changes for 0.2, in case anyone needs to hang on to 0.1.</li>
|
||||||
|
</ul>
|
||||||
|
<h3 id="010">0.1.0</h3>
|
||||||
|
<ul>
|
||||||
|
<li>Initial release.</li>
|
||||||
|
</ul>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
298
topics/rest-framework-2-announcement.html
Normal file
|
@ -0,0 +1,298 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Django REST framework 2</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Django REST framework 2">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="rest-framework-2-announcement-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 " href="../topics/2.2-announcement.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/contributing.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#django-rest-framework-2">Django REST framework 2</a></li>
|
||||||
|
<li><a href="#user-feedback">User feedback</a></li>
|
||||||
|
<li><a href="#serialization">Serialization</a></li>
|
||||||
|
<li><a href="#generic-views">Generic views</a></li>
|
||||||
|
<li><a href="#requests,-responses-&-views">Requests, Responses & Views</a></li>
|
||||||
|
<li><a href="#api-design">API Design</a></li>
|
||||||
|
<li><a href="#the-browsable-api">The Browsable API</a></li>
|
||||||
|
<li><a href="#documentation">Documentation</a></li>
|
||||||
|
<li><a href="#summary">Summary</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="django-rest-framework-2">Django REST framework 2</h1>
|
||||||
|
<p>What it is, and why you should care.</p>
|
||||||
|
<blockquote>
|
||||||
|
<p>Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.</p>
|
||||||
|
<p>— <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724">Roy Fielding</a></p>
|
||||||
|
</blockquote>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Announcement:</strong> REST framework 2 released - Tue 30th Oct 2012 </p>
|
||||||
|
<hr />
|
||||||
|
<p>REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues.</p>
|
||||||
|
<p>Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.</p>
|
||||||
|
<p>This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try.</p>
|
||||||
|
<h2 id="user-feedback">User feedback</h2>
|
||||||
|
<p>Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…</p>
|
||||||
|
<p>"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - <a href="https://twitter.com/kobutsu/status/261689665952833536">Kit La Touche</a></p>
|
||||||
|
<p>"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - <a href="https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J">Ian Strachan</a></p>
|
||||||
|
<p>"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's <em>much</em> more to my tastes" - <a href="https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ">Bruno Desthuilliers</a></p>
|
||||||
|
<p>Sounds good, right? Let's get into some details...</p>
|
||||||
|
<h2 id="serialization">Serialization</h2>
|
||||||
|
<p>REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals:</p>
|
||||||
|
<ul>
|
||||||
|
<li>A declarative serialization API, that mirrors Django's <code>Forms</code>/<code>ModelForms</code> API.</li>
|
||||||
|
<li>Structural concerns are decoupled from encoding concerns.</li>
|
||||||
|
<li>Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.</li>
|
||||||
|
<li>Validation that can be mapped to obvious and comprehensive error responses. </li>
|
||||||
|
<li>Serializers that support both nested, flat, and partially-nested representations.</li>
|
||||||
|
<li>Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it.</p>
|
||||||
|
<h2 id="generic-views">Generic views</h2>
|
||||||
|
<p>When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming <code>View</code> class, but it didn't take full advantage of the generic view implementations.</p>
|
||||||
|
<p>With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use.</p>
|
||||||
|
<h2 id="requests-responses-views">Requests, Responses & Views</h2>
|
||||||
|
<p>REST framework 2 includes <code>Request</code> and <code>Response</code> classes, than are used in place of Django's existing <code>HttpRequest</code> and <code>HttpResponse</code> classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework.</p>
|
||||||
|
<p>The <code>Request</code>/<code>Response</code> approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle.</p>
|
||||||
|
<p>REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single <code>@api_view</code> decorator, and you're good to go.</p>
|
||||||
|
<h2 id="api-design">API Design</h2>
|
||||||
|
<p>Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.</p>
|
||||||
|
<h2 id="the-browsable-api">The Browsable API</h2>
|
||||||
|
<p>Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.</p>
|
||||||
|
<p>Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.</p>
|
||||||
|
<p>With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.</p>
|
||||||
|
<p>There are also some functionality improvements - actions such as as <code>POST</code> and <code>DELETE</code> will only display if the user has the appropriate permissions.</p>
|
||||||
|
<p><img alt="Browsable API" src="../img/quickstart.png" /></p>
|
||||||
|
<p><strong>Image above</strong>: An example of the browsable API in REST framework 2</p>
|
||||||
|
<h2 id="documentation">Documentation</h2>
|
||||||
|
<p>As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.</p>
|
||||||
|
<p>We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.</p>
|
||||||
|
<h2 id="summary">Summary</h2>
|
||||||
|
<p>In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.</p>
|
||||||
|
<p>If you're interested please take a browse around the documentation. <a href="../tutorial/1-serialization.html">The tutorial</a> is a great place to get started.</p>
|
||||||
|
<p>There's also a <a href="http://restframework.herokuapp.com/">live sandbox version of the tutorial API</a> available for testing.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
266
topics/rest-hypermedia-hateoas.html
Normal file
|
@ -0,0 +1,266 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - REST, Hypermedia & HATEOAS</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, REST, Hypermedia & HATEOAS">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="rest-hypermedia-hateoas-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 " href="../topics/contributing.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../topics/browsable-api.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#rest,-hypermedia-&-hateoas">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="#building-hypermedia-apis-with-rest-framework">Building Hypermedia APIs with REST framework</a></li>
|
||||||
|
<li><a href="#what-rest-framework-provides">What REST framework provides.</a></li>
|
||||||
|
<li><a href="#what-rest-framework-doesnt-provide">What REST framework doesn't provide.</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</h1>
|
||||||
|
<blockquote>
|
||||||
|
<p>You keep using that word "REST". I do not think it means what you think it means.</p>
|
||||||
|
<p>— Mike Amundsen, <a href="http://vimeo.com/channels/restfest/page:2">REST fest 2012 keynote</a>.</p>
|
||||||
|
</blockquote>
|
||||||
|
<p>First off, the disclaimer. The name "Django REST framework" was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".</p>
|
||||||
|
<p>If you are serious about designing a Hypermedia APIs, you should look to resources outside of this documentation to help inform your design choices.</p>
|
||||||
|
<p>The following fall into the "required reading" category.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Roy Fielding's dissertation - <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Architectural Styles and
|
||||||
|
the Design of Network-based Software Architectures</a>.</li>
|
||||||
|
<li>Roy Fielding's "<a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">REST APIs must be hypertext-driven</a>" blog post.</li>
|
||||||
|
<li>Leonard Richardson & Sam Ruby's <a href="http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260">RESTful Web Services</a>.</li>
|
||||||
|
<li>Mike Amundsen's <a href="http://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578">Building Hypermedia APIs with HTML5 and Node</a>.</li>
|
||||||
|
<li>Steve Klabnik's <a href="http://designinghypermediaapis.com/">Designing Hypermedia APIs</a>.</li>
|
||||||
|
<li>The <a href="http://martinfowler.com/articles/richardsonMaturityModel.html">Richardson Maturity Model</a>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>For a more thorough background, check out Klabnik's <a href="http://blog.steveklabnik.com/posts/2012-02-27-hypermedia-api-reading-list">Hypermedia API reading list</a>.</p>
|
||||||
|
<h2 id="building-hypermedia-apis-with-rest-framework">Building Hypermedia APIs with REST framework</h2>
|
||||||
|
<p>REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.</p>
|
||||||
|
<h2 id="what-rest-framework-provides">What REST framework provides.</h2>
|
||||||
|
<p>It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.</p>
|
||||||
|
<p>REST framework also includes <a href="../api-guide/serializers.html">serialization</a> and <a href="../api-guide/parsers.html">parser</a>/<a href="../api-guide/renderers.html">renderer</a> components that make it easy to build appropriate media types, <a href="../api-guide/fields.html">hyperlinked relations</a> for building well-connected systems, and great support for <a href="../api-guide/content-negotiation.html">content negotiation</a>.</p>
|
||||||
|
<h2 id="what-rest-framework-doesnt-provide">What REST framework doesn't provide.</h2>
|
||||||
|
<p>What REST framework doesn't do is give you is machine readable hypermedia formats such as <a href="http://stateless.co/hal_specification.html">HAL</a>, <a href="http://www.amundsen.com/media-types/collection/">Collection+JSON</a>, <a href="http://jsonapi.org/">JSON API</a> or HTML <a href="http://microformats.org/wiki/Main_Page">microformats</a> by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
274
topics/writable-nested-serializers.html
Normal file
|
@ -0,0 +1,274 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Writable nested serializers</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Writable nested serializers">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="writable-nested-serializers-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 disabled" href="#">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small disabled" href="#"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#writable-nested-serializers">Writable nested serializers</a></li>
|
||||||
|
<li><a href="#one-to-many-data-structures">One-to-many data structures</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<blockquote>
|
||||||
|
<p>To save HTTP requests, it may be convenient to send related documents along with the request.</p>
|
||||||
|
<p>— <a href="http://jsonapi.org/format/#url-based-json-api">JSON API specification for Ember Data</a>.</p>
|
||||||
|
</blockquote>
|
||||||
|
<h1 id="writable-nested-serializers">Writable nested serializers</h1>
|
||||||
|
<p>Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.</p>
|
||||||
|
<p>Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependancies between the various model instances, and the need to save or delete multiple instances in a single action.</p>
|
||||||
|
<h2 id="one-to-many-data-structures">One-to-many data structures</h2>
|
||||||
|
<p><em>Example of a <strong>read-only</strong> nested serializer. Nothing complex to worry about here.</em></p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class ToDoItemSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = ToDoItem
|
||||||
|
fields = ('text', 'is_completed')
|
||||||
|
|
||||||
|
class ToDoListSerializer(serializers.ModelSerializer):
|
||||||
|
items = ToDoItemSerializer(many=True, read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ToDoList
|
||||||
|
fields = ('title', 'items')
|
||||||
|
</code></pre>
|
||||||
|
<p>Some example output from our serializer.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>{
|
||||||
|
'title': 'Leaving party preperations',
|
||||||
|
'items': {
|
||||||
|
{'text': 'Compile playlist', 'is_completed': True},
|
||||||
|
{'text': 'Send invites', 'is_completed': False},
|
||||||
|
{'text': 'Clean house', 'is_completed': False}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Let's take a look at updating our nested one-to-many data structure.</p>
|
||||||
|
<h3 id="validation-errors">Validation errors</h3>
|
||||||
|
<h3 id="adding-and-removing-items">Adding and removing items</h3>
|
||||||
|
<h3 id="making-patch-requests">Making PATCH requests</h3>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
539
tutorial/1-serialization.html
Normal file
|
@ -0,0 +1,539 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Tutorial 1: Serialization</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Tutorial 1: Serialization">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="1-serialization-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 " href="../tutorial/2-requests-and-responses.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/quickstart.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#tutorial-1-serialization">Tutorial 1: Serialization</a></li>
|
||||||
|
<li><a href="#introduction">Introduction</a></li>
|
||||||
|
<li><a href="#setting-up-a-new-environment">Setting up a new environment</a></li>
|
||||||
|
<li><a href="#getting-started">Getting started</a></li>
|
||||||
|
<li><a href="#creating-a-model-to-work-with">Creating a model to work with</a></li>
|
||||||
|
<li><a href="#creating-a-serializer-class">Creating a Serializer class</a></li>
|
||||||
|
<li><a href="#working-with-serializers">Working with Serializers</a></li>
|
||||||
|
<li><a href="#using-modelserializers">Using ModelSerializers</a></li>
|
||||||
|
<li><a href="#writing-regular-django-views-using-our-serializer">Writing regular Django views using our Serializer</a></li>
|
||||||
|
<li><a href="#testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</a></li>
|
||||||
|
<li><a href="#where-are-we-now">Where are we now</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="tutorial-1-serialization">Tutorial 1: Serialization</h1>
|
||||||
|
<h2 id="introduction">Introduction</h2>
|
||||||
|
<p>This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.</p>
|
||||||
|
<p>The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the <a href="quickstart.html">quickstart</a> documentation instead.</p>
|
||||||
|
<hr />
|
||||||
|
<p><strong>Note</strong>: The code for this tutorial is available in the <a href="https://github.com/tomchristie/rest-framework-tutorial">tomchristie/rest-framework-tutorial</a> repository on GitHub. The completed implementation is also online as a sandbox version for testing, <a href="http://restframework.herokuapp.com/">available here</a>.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="setting-up-a-new-environment">Setting up a new environment</h2>
|
||||||
|
<p>Before we do anything else we'll create a new virtual environment, using <a href="http://www.virtualenv.org/en/latest/index.html">virtualenv</a>. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.</p>
|
||||||
|
<pre class="prettyprint lang-bsh">
|
||||||
|
mkdir ~/env
|
||||||
|
virtualenv ~/env/tutorial
|
||||||
|
source ~/env/tutorial/bin/activate
|
||||||
|
</code></pre>
|
||||||
|
<p>Now that we're inside a virtualenv environment, we can install our package requirements.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>pip install django
|
||||||
|
pip install djangorestframework
|
||||||
|
pip install pygments # We'll be using this for the code highlighting
|
||||||
|
</code></pre>
|
||||||
|
<p><strong>Note:</strong> To exit the virtualenv environment at any time, just type <code>deactivate</code>. For more information see the <a href="http://www.virtualenv.org/en/latest/index.html">virtualenv documentation</a>.</p>
|
||||||
|
<h2 id="getting-started">Getting started</h2>
|
||||||
|
<p>Okay, we're ready to get coding.
|
||||||
|
To get started, let's create a new project to work with.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>cd ~
|
||||||
|
django-admin.py startproject tutorial
|
||||||
|
cd tutorial
|
||||||
|
</code></pre>
|
||||||
|
<p>Once that's done we can create an app that we'll use to create a simple Web API.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py startapp snippets
|
||||||
|
</code></pre>
|
||||||
|
<p>The simplest way to get up and running will probably be to use an <code>sqlite3</code> database for the tutorial. Edit the <code>tutorial/settings.py</code> file, and set the default database <code>"ENGINE"</code> to <code>"sqlite3"</code>, and <code>"NAME"</code> to <code>"tmp.db"</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>DATABASES = {
|
||||||
|
'default': {
|
||||||
|
'ENGINE': 'django.db.backends.sqlite3',
|
||||||
|
'NAME': 'tmp.db',
|
||||||
|
'USER': '',
|
||||||
|
'PASSWORD': '',
|
||||||
|
'HOST': '',
|
||||||
|
'PORT': '',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>We'll also need to add our new <code>snippets</code> app and the <code>rest_framework</code> app to <code>INSTALLED_APPS</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>INSTALLED_APPS = (
|
||||||
|
...
|
||||||
|
'rest_framework',
|
||||||
|
'snippets',
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>We also need to wire up the root urlconf, in the <code>tutorial/urls.py</code> file, to include our snippet app's URLs.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>urlpatterns = patterns('',
|
||||||
|
url(r'^', include('snippets.urls')),
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Okay, we're ready to roll.</p>
|
||||||
|
<h2 id="creating-a-model-to-work-with">Creating a model to work with</h2>
|
||||||
|
<p>For the purposes of this tutorial we're going to start by creating a simple <code>Snippet</code> model that is used to store code snippets. Go ahead and edit the <code>snippets</code> app's <code>models.py</code> file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.db import models
|
||||||
|
from pygments.lexers import get_all_lexers
|
||||||
|
from pygments.styles import get_all_styles
|
||||||
|
|
||||||
|
LEXERS = [item for item in get_all_lexers() if item[1]]
|
||||||
|
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
|
||||||
|
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
|
||||||
|
|
||||||
|
|
||||||
|
class Snippet(models.Model):
|
||||||
|
created = models.DateTimeField(auto_now_add=True)
|
||||||
|
title = models.CharField(max_length=100, blank=True, default='')
|
||||||
|
code = models.TextField()
|
||||||
|
linenos = models.BooleanField(default=False)
|
||||||
|
language = models.CharField(choices=LANGUAGE_CHOICES,
|
||||||
|
default='python',
|
||||||
|
max_length=100)
|
||||||
|
style = models.CharField(choices=STYLE_CHOICES,
|
||||||
|
default='friendly',
|
||||||
|
max_length=100)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
ordering = ('created',)
|
||||||
|
</code></pre>
|
||||||
|
<p>Don't forget to sync the database for the first time.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py syncdb
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="creating-a-serializer-class">Creating a Serializer class</h2>
|
||||||
|
<p>The first thing we need to get started on our Web API is provide a way of serializing and deserializing the snippet instances into representations such as <code>json</code>. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the <code>snippets</code> directory named <code>serializers.py</code> and add the following.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.forms import widgets
|
||||||
|
from rest_framework import serializers
|
||||||
|
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
|
||||||
|
|
||||||
|
|
||||||
|
class SnippetSerializer(serializers.Serializer):
|
||||||
|
pk = serializers.Field() # Note: `Field` is an untyped read-only field.
|
||||||
|
title = serializers.CharField(required=False,
|
||||||
|
max_length=100)
|
||||||
|
code = serializers.CharField(widget=widgets.Textarea,
|
||||||
|
max_length=100000)
|
||||||
|
linenos = serializers.BooleanField(required=False)
|
||||||
|
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
|
||||||
|
default='python')
|
||||||
|
style = serializers.ChoiceField(choices=STYLE_CHOICES,
|
||||||
|
default='friendly')
|
||||||
|
|
||||||
|
def restore_object(self, attrs, instance=None):
|
||||||
|
"""
|
||||||
|
Create or update a new snippet instance, given a dictionary
|
||||||
|
of deserialized field values.
|
||||||
|
|
||||||
|
Note that if we don't define this method, then deserializing
|
||||||
|
data will simply return a dictionary of items.
|
||||||
|
"""
|
||||||
|
if instance:
|
||||||
|
# Update existing instance
|
||||||
|
instance.title = attrs.get('title', instance.title)
|
||||||
|
instance.code = attrs.get('code', instance.code)
|
||||||
|
instance.linenos = attrs.get('linenos', instance.linenos)
|
||||||
|
instance.language = attrs.get('language', instance.language)
|
||||||
|
instance.style = attrs.get('style', instance.style)
|
||||||
|
return instance
|
||||||
|
|
||||||
|
# Create new instance
|
||||||
|
return Snippet(**attrs)
|
||||||
|
</code></pre>
|
||||||
|
<p>The first part of serializer class defines the fields that get serialized/deserialized. The <code>restore_object</code> method defines how fully fledged instances get created when deserializing data.</p>
|
||||||
|
<p>Notice that we can also use various attributes that would typically be used on form fields, such as <code>widget=widgets.Textarea</code>. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.</p>
|
||||||
|
<p>We can actually also save ourselves some time by using the <code>ModelSerializer</code> class, as we'll see later, but for now we'll keep our serializer definition explicit. </p>
|
||||||
|
<h2 id="working-with-serializers">Working with Serializers</h2>
|
||||||
|
<p>Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py shell
|
||||||
|
</code></pre>
|
||||||
|
<p>Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from snippets.models import Snippet
|
||||||
|
from snippets.serializers import SnippetSerializer
|
||||||
|
from rest_framework.renderers import JSONRenderer
|
||||||
|
from rest_framework.parsers import JSONParser
|
||||||
|
|
||||||
|
snippet = Snippet(code='foo = "bar"\n')
|
||||||
|
snippet.save()
|
||||||
|
|
||||||
|
snippet = Snippet(code='print "hello, world"\n')
|
||||||
|
snippet.save()
|
||||||
|
</code></pre>
|
||||||
|
<p>We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = SnippetSerializer(snippet)
|
||||||
|
serializer.data
|
||||||
|
# {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
|
||||||
|
</code></pre>
|
||||||
|
<p>At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into <code>json</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>content = JSONRenderer().render(serializer.data)
|
||||||
|
content
|
||||||
|
# '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
|
||||||
|
</code></pre>
|
||||||
|
<p>Deserialization is similar. First we parse a stream into Python native datatypes... </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>import StringIO
|
||||||
|
|
||||||
|
stream = StringIO.StringIO(content)
|
||||||
|
data = JSONParser().parse(stream)
|
||||||
|
</code></pre>
|
||||||
|
<p>...then we restore those native datatypes into to a fully populated object instance.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = SnippetSerializer(data=data)
|
||||||
|
serializer.is_valid()
|
||||||
|
# True
|
||||||
|
serializer.object
|
||||||
|
# <Snippet: Snippet object>
|
||||||
|
</code></pre>
|
||||||
|
<p>Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.</p>
|
||||||
|
<p>We can also serialize querysets instead of model instances. To do so we simply add a <code>many=True</code> flag to the serializer arguments.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
||||||
|
serializer.data
|
||||||
|
# [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="using-modelserializers">Using ModelSerializers</h2>
|
||||||
|
<p>Our <code>SnippetSerializer</code> class is replicating a lot of information that's also contained in the <code>Snippet</code> model. It would be nice if we could keep our code a bit more concise.</p>
|
||||||
|
<p>In the same way that Django provides both <code>Form</code> classes and <code>ModelForm</code> classes, REST framework includes both <code>Serializer</code> classes, and <code>ModelSerializer</code> classes.</p>
|
||||||
|
<p>Let's look at refactoring our serializer using the <code>ModelSerializer</code> class.
|
||||||
|
Open the file <code>snippets/serializers.py</code> again, and edit the <code>SnippetSerializer</code> class.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class SnippetSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Snippet
|
||||||
|
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="writing-regular-django-views-using-our-serializer">Writing regular Django views using our Serializer</h2>
|
||||||
|
<p>Let's see how we can write some API views using our new Serializer class.
|
||||||
|
For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.</p>
|
||||||
|
<p>We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into <code>json</code>.</p>
|
||||||
|
<p>Edit the <code>snippets/views.py</code> file, and add the following.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.http import HttpResponse
|
||||||
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
|
from rest_framework.renderers import JSONRenderer
|
||||||
|
from rest_framework.parsers import JSONParser
|
||||||
|
from snippets.models import Snippet
|
||||||
|
from snippets.serializers import SnippetSerializer
|
||||||
|
|
||||||
|
class JSONResponse(HttpResponse):
|
||||||
|
"""
|
||||||
|
An HttpResponse that renders its content into JSON.
|
||||||
|
"""
|
||||||
|
def __init__(self, data, **kwargs):
|
||||||
|
content = JSONRenderer().render(data)
|
||||||
|
kwargs['content_type'] = 'application/json'
|
||||||
|
super(JSONResponse, self).__init__(content, **kwargs)
|
||||||
|
</code></pre>
|
||||||
|
<p>The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@csrf_exempt
|
||||||
|
def snippet_list(request):
|
||||||
|
"""
|
||||||
|
List all code snippets, or create a new snippet.
|
||||||
|
"""
|
||||||
|
if request.method == 'GET':
|
||||||
|
snippets = Snippet.objects.all()
|
||||||
|
serializer = SnippetSerializer(snippets, many=True)
|
||||||
|
return JSONResponse(serializer.data)
|
||||||
|
|
||||||
|
elif request.method == 'POST':
|
||||||
|
data = JSONParser().parse(request)
|
||||||
|
serializer = SnippetSerializer(data=data)
|
||||||
|
if serializer.is_valid():
|
||||||
|
serializer.save()
|
||||||
|
return JSONResponse(serializer.data, status=201)
|
||||||
|
else:
|
||||||
|
return JSONResponse(serializer.errors, status=400)
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as <code>csrf_exempt</code>. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now. </p>
|
||||||
|
<p>We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@csrf_exempt
|
||||||
|
def snippet_detail(request, pk):
|
||||||
|
"""
|
||||||
|
Retrieve, update or delete a code snippet.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
snippet = Snippet.objects.get(pk=pk)
|
||||||
|
except Snippet.DoesNotExist:
|
||||||
|
return HttpResponse(status=404)
|
||||||
|
|
||||||
|
if request.method == 'GET':
|
||||||
|
serializer = SnippetSerializer(snippet)
|
||||||
|
return JSONResponse(serializer.data)
|
||||||
|
|
||||||
|
elif request.method == 'PUT':
|
||||||
|
data = JSONParser().parse(request)
|
||||||
|
serializer = SnippetSerializer(snippet, data=data)
|
||||||
|
if serializer.is_valid():
|
||||||
|
serializer.save()
|
||||||
|
return JSONResponse(serializer.data)
|
||||||
|
else:
|
||||||
|
return JSONResponse(serializer.errors, status=400)
|
||||||
|
|
||||||
|
elif request.method == 'DELETE':
|
||||||
|
snippet.delete()
|
||||||
|
return HttpResponse(status=204)
|
||||||
|
</code></pre>
|
||||||
|
<p>Finally we need to wire these views up. Create the <code>snippets/urls.py</code> file:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url
|
||||||
|
|
||||||
|
urlpatterns = patterns('snippets.views',
|
||||||
|
url(r'^snippets/$', 'snippet_list'),
|
||||||
|
url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed <code>json</code>, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.</p>
|
||||||
|
<h2 id="testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</h2>
|
||||||
|
<p>Now we can start up a sample server that serves our snippets.</p>
|
||||||
|
<p>Quit out of the shell...</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>quit()
|
||||||
|
</code></pre>
|
||||||
|
<p>...and start up Django's development server.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py runserver
|
||||||
|
|
||||||
|
Validating models...
|
||||||
|
|
||||||
|
0 errors found
|
||||||
|
Django version 1.4.3, using settings 'tutorial.settings'
|
||||||
|
Development server is running at http://127.0.0.1:8000/
|
||||||
|
Quit the server with CONTROL-C.
|
||||||
|
</code></pre>
|
||||||
|
<p>In another terminal window, we can test the server.</p>
|
||||||
|
<p>We can get a list of all of the snippets.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/
|
||||||
|
|
||||||
|
[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
|
||||||
|
</code></pre>
|
||||||
|
<p>Or we can get a particular snippet by referencing its id.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/2/
|
||||||
|
|
||||||
|
{"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
|
||||||
|
</code></pre>
|
||||||
|
<p>Similarly, you can have the same json displayed by visiting these URLs in a web browser.</p>
|
||||||
|
<h2 id="where-are-we-now">Where are we now</h2>
|
||||||
|
<p>We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.</p>
|
||||||
|
<p>Our API views don't do anything particularly special at the moment, beyond serving <code>json</code> responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.</p>
|
||||||
|
<p>We'll see how we can start to improve things in <a href="2-requests-and-responses.html">part 2 of the tutorial</a>.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
379
tutorial/2-requests-and-responses.html
Normal file
|
@ -0,0 +1,379 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Tutorial 2: Requests and Responses</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Tutorial 2: Requests and Responses">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="2-requests-and-responses-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 " href="../tutorial/3-class-based-views.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/1-serialization.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</a></li>
|
||||||
|
<li><a href="#request-objects">Request objects</a></li>
|
||||||
|
<li><a href="#response-objects">Response objects</a></li>
|
||||||
|
<li><a href="#status-codes">Status codes</a></li>
|
||||||
|
<li><a href="#wrapping-api-views">Wrapping API views</a></li>
|
||||||
|
<li><a href="#pulling-it-all-together">Pulling it all together</a></li>
|
||||||
|
<li><a href="#adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</a></li>
|
||||||
|
<li><a href="#hows-it-looking">How's it looking?</a></li>
|
||||||
|
<li><a href="#whats-next">What's next?</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="tutorial-2-requests-and-responses">Tutorial 2: Requests and Responses</h1>
|
||||||
|
<p>From this point we're going to really start covering the core of REST framework.
|
||||||
|
Let's introduce a couple of essential building blocks.</p>
|
||||||
|
<h2 id="request-objects">Request objects</h2>
|
||||||
|
<p>REST framework introduces a <code>Request</code> object that extends the regular <code>HttpRequest</code>, and provides more flexible request parsing. The core functionality of the <code>Request</code> object is the <code>request.DATA</code> attribute, which is similar to <code>request.POST</code>, but more useful for working with Web APIs.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>request.POST # Only handles form data. Only works for 'POST' method.
|
||||||
|
request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="response-objects">Response objects</h2>
|
||||||
|
<p>REST framework also introduces a <code>Response</code> object, which is a type of <code>TemplateResponse</code> that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>return Response(data) # Renders to content type as requested by the client.
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="status-codes">Status codes</h2>
|
||||||
|
<p>Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as <code>HTTP_400_BAD_REQUEST</code> in the <code>status</code> module. It's a good idea to use these throughout rather than using numeric identifiers.</p>
|
||||||
|
<h2 id="wrapping-api-views">Wrapping API views</h2>
|
||||||
|
<p>REST framework provides two wrappers you can use to write API views.</p>
|
||||||
|
<ol>
|
||||||
|
<li>The <code>@api_view</code> decorator for working with function based views.</li>
|
||||||
|
<li>The <code>APIView</code> class for working with class based views.</li>
|
||||||
|
</ol>
|
||||||
|
<p>These wrappers provide a few bits of functionality such as making sure you receive <code>Request</code> instances in your view, and adding context to <code>Response</code> objects so that content negotiation can be performed.</p>
|
||||||
|
<p>The wrappers also provide behaviour such as returning <code>405 Method Not Allowed</code> responses when appropriate, and handling any <code>ParseError</code> exception that occurs when accessing <code>request.DATA</code> with malformed input.</p>
|
||||||
|
<h2 id="pulling-it-all-together">Pulling it all together</h2>
|
||||||
|
<p>Okay, let's go ahead and start using these new components to write a few views. </p>
|
||||||
|
<p>We don't need our <code>JSONResponse</code> class in <code>views.py</code> anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import status
|
||||||
|
from rest_framework.decorators import api_view
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from snippets.models import Snippet
|
||||||
|
from snippets.serializers import SnippetSerializer
|
||||||
|
|
||||||
|
|
||||||
|
@api_view(['GET', 'POST'])
|
||||||
|
def snippet_list(request):
|
||||||
|
"""
|
||||||
|
List all snippets, or create a new snippet.
|
||||||
|
"""
|
||||||
|
if request.method == 'GET':
|
||||||
|
snippets = Snippet.objects.all()
|
||||||
|
serializer = SnippetSerializer(snippets, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
elif request.method == 'POST':
|
||||||
|
serializer = SnippetSerializer(data=request.DATA)
|
||||||
|
if serializer.is_valid():
|
||||||
|
serializer.save()
|
||||||
|
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||||
|
else:
|
||||||
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
</code></pre>
|
||||||
|
<p>Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.</p>
|
||||||
|
<p>Here is the view for an individual snippet, in the <code>views.py</code> module.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>@api_view(['GET', 'PUT', 'DELETE'])
|
||||||
|
def snippet_detail(request, pk):
|
||||||
|
"""
|
||||||
|
Retrieve, update or delete a snippet instance.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
snippet = Snippet.objects.get(pk=pk)
|
||||||
|
except Snippet.DoesNotExist:
|
||||||
|
return Response(status=status.HTTP_404_NOT_FOUND)
|
||||||
|
|
||||||
|
if request.method == 'GET':
|
||||||
|
serializer = SnippetSerializer(snippet)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
elif request.method == 'PUT':
|
||||||
|
serializer = SnippetSerializer(snippet, data=request.DATA)
|
||||||
|
if serializer.is_valid():
|
||||||
|
serializer.save()
|
||||||
|
return Response(serializer.data)
|
||||||
|
else:
|
||||||
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
elif request.method == 'DELETE':
|
||||||
|
snippet.delete()
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
</code></pre>
|
||||||
|
<p>This should all feel very familiar - it is not a lot different from working with regular Django views.</p>
|
||||||
|
<p>Notice that we're no longer explicitly tying our requests or responses to a given content type. <code>request.DATA</code> can handle incoming <code>json</code> requests, but it can also handle <code>yaml</code> and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.</p>
|
||||||
|
<h2 id="adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</h2>
|
||||||
|
<p>To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as <a href="http://example.com/api/items/4.json">http://example.com/api/items/4.json</a>.</p>
|
||||||
|
<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def snippet_list(request, format=None):
|
||||||
|
</code></pre>
|
||||||
|
<p>and</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def snippet_detail(request, pk, format=None):
|
||||||
|
</code></pre>
|
||||||
|
<p>Now update the <code>urls.py</code> file slightly, to append a set of <code>format_suffix_patterns</code> in addition to the existing URLs.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url
|
||||||
|
from rest_framework.urlpatterns import format_suffix_patterns
|
||||||
|
|
||||||
|
urlpatterns = patterns('snippets.views',
|
||||||
|
url(r'^snippets/$', 'snippet_list'),
|
||||||
|
url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'),
|
||||||
|
)
|
||||||
|
|
||||||
|
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||||
|
</code></pre>
|
||||||
|
<p>We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.</p>
|
||||||
|
<h2 id="hows-it-looking">How's it looking?</h2>
|
||||||
|
<p>Go ahead and test the API from the command line, as we did in <a href="1-serialization.html">tutorial part 1</a>. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.</p>
|
||||||
|
<p>We can get a list of all of the snippets, as before.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/
|
||||||
|
|
||||||
|
[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
|
||||||
|
</code></pre>
|
||||||
|
<p>We can control the format of the response that we get back, either by using the <code>Accept</code> header:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json' # Request JSON
|
||||||
|
curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html' # Request HTML
|
||||||
|
</code></pre>
|
||||||
|
<p>Or by appending a format suffix:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl http://127.0.0.1:8000/snippets/.json # JSON suffix
|
||||||
|
curl http://127.0.0.1:8000/snippets/.api # Browsable API suffix
|
||||||
|
</code></pre>
|
||||||
|
<p>Similarly, we can control the format of the request that we send, using the <code>Content-Type</code> header.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># POST using form data
|
||||||
|
curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
|
||||||
|
|
||||||
|
{"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"}
|
||||||
|
|
||||||
|
# POST using JSON
|
||||||
|
curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json"
|
||||||
|
|
||||||
|
{"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"}
|
||||||
|
</code></pre>
|
||||||
|
<p>Now go and open the API in a web browser, by visiting <a href="http://127.0.0.1:8000/snippets/">http://127.0.0.1:8000/snippets/</a>.</p>
|
||||||
|
<h3 id="browsability">Browsability</h3>
|
||||||
|
<p>Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.</p>
|
||||||
|
<p>Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.</p>
|
||||||
|
<p>See the <a href="../topics/browsable-api.html">browsable api</a> topic for more information about the browsable API feature and how to customize it.</p>
|
||||||
|
<h2 id="whats-next">What's next?</h2>
|
||||||
|
<p>In <a href="3-class-based-views.html">tutorial part 3</a>, we'll start using class based views, and see how generic views reduce the amount of code we need to write.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
370
tutorial/3-class-based-views.html
Normal file
|
@ -0,0 +1,370 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Tutorial 3: Class Based Views</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Tutorial 3: Class Based Views">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="3-class-based-views-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 " href="../tutorial/4-authentication-and-permissions.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/2-requests-and-responses.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#tutorial-3-class-based-views">Tutorial 3: Class Based Views</a></li>
|
||||||
|
<li><a href="#rewriting-our-api-using-class-based-views">Rewriting our API using class based views</a></li>
|
||||||
|
<li><a href="#using-mixins">Using mixins</a></li>
|
||||||
|
<li><a href="#using-generic-class-based-views">Using generic class based views</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="tutorial-3-class-based-views">Tutorial 3: Class Based Views</h1>
|
||||||
|
<p>We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>.</p>
|
||||||
|
<h2 id="rewriting-our-api-using-class-based-views">Rewriting our API using class based views</h2>
|
||||||
|
<p>We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring of <code>views.py</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from snippets.models import Snippet
|
||||||
|
from snippets.serializers import SnippetSerializer
|
||||||
|
from django.http import Http404
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework import status
|
||||||
|
|
||||||
|
|
||||||
|
class SnippetList(APIView):
|
||||||
|
"""
|
||||||
|
List all snippets, or create a new snippet.
|
||||||
|
"""
|
||||||
|
def get(self, request, format=None):
|
||||||
|
snippets = Snippet.objects.all()
|
||||||
|
serializer = SnippetSerializer(snippets, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
def post(self, request, format=None):
|
||||||
|
serializer = SnippetSerializer(data=request.DATA)
|
||||||
|
if serializer.is_valid():
|
||||||
|
serializer.save()
|
||||||
|
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||||
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
</code></pre>
|
||||||
|
<p>So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in <code>views.py</code>. </p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class SnippetDetail(APIView):
|
||||||
|
"""
|
||||||
|
Retrieve, update or delete a snippet instance.
|
||||||
|
"""
|
||||||
|
def get_object(self, pk):
|
||||||
|
try:
|
||||||
|
return Snippet.objects.get(pk=pk)
|
||||||
|
except Snippet.DoesNotExist:
|
||||||
|
raise Http404
|
||||||
|
|
||||||
|
def get(self, request, pk, format=None):
|
||||||
|
snippet = self.get_object(pk)
|
||||||
|
serializer = SnippetSerializer(snippet)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
def put(self, request, pk, format=None):
|
||||||
|
snippet = self.get_object(pk)
|
||||||
|
serializer = SnippetSerializer(snippet, data=request.DATA)
|
||||||
|
if serializer.is_valid():
|
||||||
|
serializer.save()
|
||||||
|
return Response(serializer.data)
|
||||||
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
def delete(self, request, pk, format=None):
|
||||||
|
snippet = self.get_object(pk)
|
||||||
|
snippet.delete()
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
</code></pre>
|
||||||
|
<p>That's looking good. Again, it's still pretty similar to the function based view right now.</p>
|
||||||
|
<p>We'll also need to refactor our <code>urls.py</code> slightly now we're using class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url
|
||||||
|
from rest_framework.urlpatterns import format_suffix_patterns
|
||||||
|
from snippets import views
|
||||||
|
|
||||||
|
urlpatterns = patterns('',
|
||||||
|
url(r'^snippets/$', views.SnippetList.as_view()),
|
||||||
|
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
|
||||||
|
)
|
||||||
|
|
||||||
|
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||||
|
</code></pre>
|
||||||
|
<p>Okay, we're done. If you run the development server everything should be working just as before.</p>
|
||||||
|
<h2 id="using-mixins">Using mixins</h2>
|
||||||
|
<p>One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.</p>
|
||||||
|
<p>The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.</p>
|
||||||
|
<p>Let's take a look at how we can compose the views by using the mixin classes. Here's our <code>views.py</code> module again.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from snippets.models import Snippet
|
||||||
|
from snippets.serializers import SnippetSerializer
|
||||||
|
from rest_framework import mixins
|
||||||
|
from rest_framework import generics
|
||||||
|
|
||||||
|
class SnippetList(mixins.ListModelMixin,
|
||||||
|
mixins.CreateModelMixin,
|
||||||
|
generics.GenericAPIView):
|
||||||
|
queryset = Snippet.objects.all()
|
||||||
|
serializer_class = SnippetSerializer
|
||||||
|
|
||||||
|
def get(self, request, *args, **kwargs):
|
||||||
|
return self.list(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def post(self, request, *args, **kwargs):
|
||||||
|
return self.create(request, *args, **kwargs)
|
||||||
|
</code></pre>
|
||||||
|
<p>We'll take a moment to examine exactly what's happening here. We're building our view using <code>GenericAPIView</code>, and adding in <code>ListModelMixin</code> and <code>CreateModelMixin</code>.</p>
|
||||||
|
<p>The base class provides the core functionality, and the mixin classes provide the <code>.list()</code> and <code>.create()</code> actions. We're then explicitly binding the <code>get</code> and <code>post</code> methods to the appropriate actions. Simple enough stuff so far.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class SnippetDetail(mixins.RetrieveModelMixin,
|
||||||
|
mixins.UpdateModelMixin,
|
||||||
|
mixins.DestroyModelMixin,
|
||||||
|
generics.GenericAPIView):
|
||||||
|
queryset = Snippet.objects.all()
|
||||||
|
serializer_class = SnippetSerializer
|
||||||
|
|
||||||
|
def get(self, request, *args, **kwargs):
|
||||||
|
return self.retrieve(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def put(self, request, *args, **kwargs):
|
||||||
|
return self.update(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def delete(self, request, *args, **kwargs):
|
||||||
|
return self.destroy(request, *args, **kwargs)
|
||||||
|
</code></pre>
|
||||||
|
<p>Pretty similar. Again we're using the <code>GenericAPIView</code> class to provide the core functionality, and adding in mixins to provide the <code>.retrieve()</code>, <code>.update()</code> and <code>.destroy()</code> actions.</p>
|
||||||
|
<h2 id="using-generic-class-based-views">Using generic class based views</h2>
|
||||||
|
<p>Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our <code>views.py</code> module even more.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from snippets.models import Snippet
|
||||||
|
from snippets.serializers import SnippetSerializer
|
||||||
|
from rest_framework import generics
|
||||||
|
|
||||||
|
|
||||||
|
class SnippetList(generics.ListCreateAPIView):
|
||||||
|
queryset = Snippet.objects.all()
|
||||||
|
serializer_class = SnippetSerializer
|
||||||
|
|
||||||
|
|
||||||
|
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||||
|
queryset = Snippet.objects.all()
|
||||||
|
serializer_class = SnippetSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.</p>
|
||||||
|
<p>Next we'll move onto <a href="4-authentication-and-permissions.html">part 4 of the tutorial</a>, where we'll take a look at how we can deal with authentication and permissions for our API.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
403
tutorial/4-authentication-and-permissions.html
Normal file
|
@ -0,0 +1,403 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Tutorial 4: Authentication & Permissions</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Tutorial 4: Authentication & Permissions">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="4-authentication-and-permissions-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 " href="../tutorial/5-relationships-and-hyperlinked-apis.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/3-class-based-views.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#tutorial-4-authentication-&-permissions">Tutorial 4: Authentication & Permissions</a></li>
|
||||||
|
<li><a href="#adding-information-to-our-model">Adding information to our model</a></li>
|
||||||
|
<li><a href="#adding-endpoints-for-our-user-models">Adding endpoints for our User models</a></li>
|
||||||
|
<li><a href="#associating-snippets-with-users">Associating Snippets with Users</a></li>
|
||||||
|
<li><a href="#updating-our-serializer">Updating our serializer</a></li>
|
||||||
|
<li><a href="#adding-required-permissions-to-views">Adding required permissions to views</a></li>
|
||||||
|
<li><a href="#adding-login-to-the-browsable-api">Adding login to the Browsable API</a></li>
|
||||||
|
<li><a href="#object-level-permissions">Object level permissions</a></li>
|
||||||
|
<li><a href="#authenticating-with-the-api">Authenticating with the API</a></li>
|
||||||
|
<li><a href="#summary">Summary</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="tutorial-4-authentication-permissions">Tutorial 4: Authentication & Permissions</h1>
|
||||||
|
<p>Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Code snippets are always associated with a creator.</li>
|
||||||
|
<li>Only authenticated users may create snippets.</li>
|
||||||
|
<li>Only the creator of a snippet may update or delete it.</li>
|
||||||
|
<li>Unauthenticated requests should have full read-only access.</li>
|
||||||
|
</ul>
|
||||||
|
<h2 id="adding-information-to-our-model">Adding information to our model</h2>
|
||||||
|
<p>We're going to make a couple of changes to our <code>Snippet</code> model class.
|
||||||
|
First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.</p>
|
||||||
|
<p>Add the following two fields to the <code>Snippet</code> model in <code>models.py</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>owner = models.ForeignKey('auth.User', related_name='snippets')
|
||||||
|
highlighted = models.TextField()
|
||||||
|
</code></pre>
|
||||||
|
<p>We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the <code>pygments</code> code highlighting library.</p>
|
||||||
|
<p>We'll need some extra imports:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from pygments.lexers import get_lexer_by_name
|
||||||
|
from pygments.formatters.html import HtmlFormatter
|
||||||
|
from pygments import highlight
|
||||||
|
</code></pre>
|
||||||
|
<p>And now we can add a <code>.save()</code> method to our model class:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def save(self, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
Use the `pygments` library to create a highlighted HTML
|
||||||
|
representation of the code snippet.
|
||||||
|
"""
|
||||||
|
lexer = get_lexer_by_name(self.language)
|
||||||
|
linenos = self.linenos and 'table' or False
|
||||||
|
options = self.title and {'title': self.title} or {}
|
||||||
|
formatter = HtmlFormatter(style=self.style, linenos=linenos,
|
||||||
|
full=True, **options)
|
||||||
|
self.highlighted = highlight(self.code, lexer, formatter)
|
||||||
|
super(Snippet, self).save(*args, **kwargs)
|
||||||
|
</code></pre>
|
||||||
|
<p>When that's all done we'll need to update our database tables.
|
||||||
|
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>rm tmp.db
|
||||||
|
python ./manage.py syncdb
|
||||||
|
</code></pre>
|
||||||
|
<p>You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the <code>createsuperuser</code> command.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python ./manage.py createsuperuser
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="adding-endpoints-for-our-user-models">Adding endpoints for our User models</h2>
|
||||||
|
<p>Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In <code>serializers.py</code> add:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||||||
|
|
||||||
|
class UserSerializer(serializers.ModelSerializer):
|
||||||
|
snippets = serializers.PrimaryKeyRelatedField(many=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ('id', 'username', 'snippets')
|
||||||
|
</code></pre>
|
||||||
|
<p>Because <code>'snippets'</code> is a <em>reverse</em> relationship on the User model, it will not be included by default when using the <code>ModelSerializer</code> class, so we needed to add an explicit field for it.</p>
|
||||||
|
<p>We'll also add a couple of views to <code>views.py</code>. We'd like to just use read-only views for the user representations, so we'll use the <code>ListAPIView</code> and <code>RetrieveAPIView</code> generic class based views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class UserList(generics.ListAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
|
||||||
|
|
||||||
|
class UserDetail(generics.RetrieveAPIView):
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>Make sure to also import the <code>UserSerializer</code> class</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from snippets.serializers import UserSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in <code>urls.py</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>url(r'^users/$', views.UserList.as_view()),
|
||||||
|
url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="associating-snippets-with-users">Associating Snippets with Users</h2>
|
||||||
|
<p>Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.</p>
|
||||||
|
<p>The way we deal with that is by overriding a <code>.pre_save()</code> method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.</p>
|
||||||
|
<p>On <strong>both</strong> the <code>SnippetList</code> and <code>SnippetDetail</code> view classes, add the following method:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>def pre_save(self, obj):
|
||||||
|
obj.owner = self.request.user
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="updating-our-serializer">Updating our serializer</h2>
|
||||||
|
<p>Now that snippets are associated with the user that created them, let's update our <code>SnippetSerializer</code> to reflect that. Add the following field to the serializer definition in <code>serializers.py</code>:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>owner = serializers.Field(source='owner.username')
|
||||||
|
</code></pre>
|
||||||
|
<p><strong>Note</strong>: Make sure you also add <code>'owner',</code> to the list of fields in the inner <code>Meta</code> class.</p>
|
||||||
|
<p>This field is doing something quite interesting. The <code>source</code> argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.</p>
|
||||||
|
<p>The field we've added is the untyped <code>Field</code> class, in contrast to the other typed fields, such as <code>CharField</code>, <code>BooleanField</code> etc... The untyped <code>Field</code> is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.</p>
|
||||||
|
<h2 id="adding-required-permissions-to-views">Adding required permissions to views</h2>
|
||||||
|
<p>Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.</p>
|
||||||
|
<p>REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is <code>IsAuthenticatedOrReadOnly</code>, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.</p>
|
||||||
|
<p>First add the following import in the views module</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import permissions
|
||||||
|
</code></pre>
|
||||||
|
<p>Then, add the following property to <strong>both</strong> the <code>SnippetList</code> and <code>SnippetDetail</code> view classes.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="adding-login-to-the-browsable-api">Adding login to the Browsable API</h2>
|
||||||
|
<p>If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.</p>
|
||||||
|
<p>We can add a login view for use with the browsable API, by editing our URLconf once more.</p>
|
||||||
|
<p>Add the following import at the top of the file:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import include
|
||||||
|
</code></pre>
|
||||||
|
<p>And, at the end of the file, add a pattern to include the login and logout views for the browsable API.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>urlpatterns += patterns('',
|
||||||
|
url(r'^api-auth/', include('rest_framework.urls',
|
||||||
|
namespace='rest_framework')),
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>The <code>r'^api-auth/'</code> part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the <code>'rest_framework'</code> namespace.</p>
|
||||||
|
<p>Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.</p>
|
||||||
|
<p>Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.</p>
|
||||||
|
<h2 id="object-level-permissions">Object level permissions</h2>
|
||||||
|
<p>Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.</p>
|
||||||
|
<p>To do that we're going to need to create a custom permission.</p>
|
||||||
|
<p>In the snippets app, create a new file, <code>permissions.py</code></p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import permissions
|
||||||
|
|
||||||
|
|
||||||
|
class IsOwnerOrReadOnly(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Custom permission to only allow owners of an object to edit it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def has_object_permission(self, request, view, obj):
|
||||||
|
# Read permissions are allowed to any request,
|
||||||
|
# so we'll always allow GET, HEAD or OPTIONS requests.
|
||||||
|
if request.method in permissions.SAFE_METHODS:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Write permissions are only allowed to the owner of the snippet
|
||||||
|
return obj.owner == request.user
|
||||||
|
</code></pre>
|
||||||
|
<p>Now we can add that custom permission to our snippet instance endpoint, by editing the <code>permission_classes</code> property on the <code>SnippetDetail</code> class:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>permission_classes = (permissions.IsAuthenticatedOrReadOnly,
|
||||||
|
IsOwnerOrReadOnly,)
|
||||||
|
</code></pre>
|
||||||
|
<p>Make sure to also import the <code>IsOwnerOrReadOnly</code> class.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from snippets.permissions import IsOwnerOrReadOnly
|
||||||
|
</code></pre>
|
||||||
|
<p>Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.</p>
|
||||||
|
<h2 id="authenticating-with-the-api">Authenticating with the API</h2>
|
||||||
|
<p>Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any <a href="../api-guide/authentication.html">authentication classes</a>, so the defaults are currently applied, which are <code>SessionAuthentication</code> and <code>BasicAuthentication</code>.</p>
|
||||||
|
<p>When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.</p>
|
||||||
|
<p>If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.</p>
|
||||||
|
<p>If we try to create a snippet without authenticating, we'll get an error:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
|
||||||
|
|
||||||
|
{"detail": "Authentication credentials were not provided."}
|
||||||
|
</code></pre>
|
||||||
|
<p>We can make a successful request by including the username and password of one of the users we created earlier.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password
|
||||||
|
|
||||||
|
{"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"}
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="summary">Summary</h2>
|
||||||
|
<p>We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.</p>
|
||||||
|
<p>In <a href="5-relationships-and-hyperlinked-apis.html">part 5</a> of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
372
tutorial/5-relationships-and-hyperlinked-apis.html
Normal file
|
@ -0,0 +1,372 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Tutorial 5: Relationships & Hyperlinked APIs</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Tutorial 5: Relationships & Hyperlinked APIs">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="5-relationships-and-hyperlinked-apis-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 " href="../tutorial/6-viewsets-and-routers.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/4-authentication-and-permissions.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#tutorial-5-relationships-&-hyperlinked-apis">Tutorial 5: Relationships & Hyperlinked APIs</a></li>
|
||||||
|
<li><a href="#creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</a></li>
|
||||||
|
<li><a href="#creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</a></li>
|
||||||
|
<li><a href="#hyperlinking-our-api">Hyperlinking our API</a></li>
|
||||||
|
<li><a href="#making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</a></li>
|
||||||
|
<li><a href="#adding-pagination">Adding pagination</a></li>
|
||||||
|
<li><a href="#browsing-the-api">Browsing the API</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="tutorial-5-relationships-hyperlinked-apis">Tutorial 5: Relationships & Hyperlinked APIs</h1>
|
||||||
|
<p>At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships. </p>
|
||||||
|
<h2 id="creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</h2>
|
||||||
|
<p>Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the <code>@api_view</code> decorator we introduced earlier.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import renderers
|
||||||
|
from rest_framework.decorators import api_view
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.reverse import reverse
|
||||||
|
|
||||||
|
|
||||||
|
@api_view(('GET',))
|
||||||
|
def api_root(request, format=None):
|
||||||
|
return Response({
|
||||||
|
'users': reverse('user-list', request=request, format=format),
|
||||||
|
'snippets': reverse('snippet-list', request=request, format=format)
|
||||||
|
})
|
||||||
|
</code></pre>
|
||||||
|
<p>Notice that we're using REST framework's <code>reverse</code> function in order to return fully-qualified URLs.</p>
|
||||||
|
<h2 id="creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</h2>
|
||||||
|
<p>The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.</p>
|
||||||
|
<p>Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.</p>
|
||||||
|
<p>The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.</p>
|
||||||
|
<p>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own <code>.get()</code> method. In your snippets.views add:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import renderers
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
class SnippetHighlight(generics.GenericAPIView):
|
||||||
|
queryset = Snippet.objects.all()
|
||||||
|
renderer_classes = (renderers.StaticHTMLRenderer,)
|
||||||
|
|
||||||
|
def get(self, request, *args, **kwargs):
|
||||||
|
snippet = self.get_object()
|
||||||
|
return Response(snippet.highlighted)
|
||||||
|
</code></pre>
|
||||||
|
<p>As usual we need to add the new views that we've created in to our URLconf.
|
||||||
|
We'll add a url pattern for our new API root:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>url(r'^$', 'api_root'),
|
||||||
|
</code></pre>
|
||||||
|
<p>And then add a url pattern for the snippet highlights:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="hyperlinking-our-api">Hyperlinking our API</h2>
|
||||||
|
<p>Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Using primary keys.</li>
|
||||||
|
<li>Using hyperlinking between entities.</li>
|
||||||
|
<li>Using a unique identifying slug field on the related entity.</li>
|
||||||
|
<li>Using the default string representation of the related entity.</li>
|
||||||
|
<li>Nesting the related entity inside the parent representation.</li>
|
||||||
|
<li>Some other custom representation.</li>
|
||||||
|
</ul>
|
||||||
|
<p>REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.</p>
|
||||||
|
<p>In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend <code>HyperlinkedModelSerializer</code> instead of the existing <code>ModelSerializer</code>.</p>
|
||||||
|
<p>The <code>HyperlinkedModelSerializer</code> has the following differences from <code>ModelSerializer</code>:</p>
|
||||||
|
<ul>
|
||||||
|
<li>It does not include the <code>pk</code> field by default.</li>
|
||||||
|
<li>It includes a <code>url</code> field, using <code>HyperlinkedIdentityField</code>.</li>
|
||||||
|
<li>Relationships use <code>HyperlinkedRelatedField</code>,
|
||||||
|
instead of <code>PrimaryKeyRelatedField</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>We can easily re-write our existing serializers to use hyperlinking.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>class SnippetSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
owner = serializers.Field(source='owner.username')
|
||||||
|
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Snippet
|
||||||
|
fields = ('url', 'highlight', 'owner',
|
||||||
|
'title', 'code', 'linenos', 'language', 'style')
|
||||||
|
|
||||||
|
|
||||||
|
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ('url', 'username', 'snippets')
|
||||||
|
</code></pre>
|
||||||
|
<p>Notice that we've also added a new <code>'highlight'</code> field. This field is of the same type as the <code>url</code> field, except that it points to the <code>'snippet-highlight'</code> url pattern, instead of the <code>'snippet-detail'</code> url pattern.</p>
|
||||||
|
<p>Because we've included format suffixed URLs such as <code>'.json'</code>, we also need to indicate on the <code>highlight</code> field that any format suffixed hyperlinks it returns should use the <code>'.html'</code> suffix.</p>
|
||||||
|
<h2 id="making-sure-our-url-patterns-are-named">Making sure our URL patterns are named</h2>
|
||||||
|
<p>If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.</p>
|
||||||
|
<ul>
|
||||||
|
<li>The root of our API refers to <code>'user-list'</code> and <code>'snippet-list'</code>.</li>
|
||||||
|
<li>Our snippet serializer includes a field that refers to <code>'snippet-highlight'</code>.</li>
|
||||||
|
<li>Our user serializer includes a field that refers to <code>'snippet-detail'</code>.</li>
|
||||||
|
<li>Our snippet and user serializers include <code>'url'</code> fields that by default will refer to <code>'{model_name}-detail'</code>, which in this case will be <code>'snippet-detail'</code> and <code>'user-detail'</code>.</li>
|
||||||
|
</ul>
|
||||||
|
<p>After adding all those names into our URLconf, our final <code>'urls.py'</code> file should look something like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># API endpoints
|
||||||
|
urlpatterns = format_suffix_patterns(patterns('snippets.views',
|
||||||
|
url(r'^$', 'api_root'),
|
||||||
|
url(r'^snippets/$',
|
||||||
|
views.SnippetList.as_view(),
|
||||||
|
name='snippet-list'),
|
||||||
|
url(r'^snippets/(?P<pk>[0-9]+)/$',
|
||||||
|
views.SnippetDetail.as_view(),
|
||||||
|
name='snippet-detail'),
|
||||||
|
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
|
||||||
|
views.SnippetHighlight.as_view(),
|
||||||
|
name='snippet-highlight'),
|
||||||
|
url(r'^users/$',
|
||||||
|
views.UserList.as_view(),
|
||||||
|
name='user-list'),
|
||||||
|
url(r'^users/(?P<pk>[0-9]+)/$',
|
||||||
|
views.UserDetail.as_view(),
|
||||||
|
name='user-detail')
|
||||||
|
))
|
||||||
|
|
||||||
|
# Login and logout views for the browsable API
|
||||||
|
urlpatterns += patterns('',
|
||||||
|
url(r'^api-auth/', include('rest_framework.urls',
|
||||||
|
namespace='rest_framework')),
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="adding-pagination">Adding pagination</h2>
|
||||||
|
<p>The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.</p>
|
||||||
|
<p>We can change the default list style to use pagination, by modifying our <code>settings.py</code> file slightly. Add the following setting:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||||
|
'PAGINATE_BY': 10
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.</p>
|
||||||
|
<p>We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.</p>
|
||||||
|
<h2 id="browsing-the-api">Browsing the API</h2>
|
||||||
|
<p>If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.</p>
|
||||||
|
<p>You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.</p>
|
||||||
|
<p>In <a href="6-viewsets-and-routers.html">part 6</a> of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
361
tutorial/6-viewsets-and-routers.html
Normal file
|
@ -0,0 +1,361 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Tutorial 6: ViewSets & Routers</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Tutorial 6: ViewSets & Routers">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="6-viewsets-and-routers-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 " href="../api-guide/requests.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../tutorial/5-relationships-and-hyperlinked-apis.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#tutorial-6-viewsets-&-routers">Tutorial 6: ViewSets & Routers</a></li>
|
||||||
|
<li><a href="#refactoring-to-use-viewsets">Refactoring to use ViewSets</a></li>
|
||||||
|
<li><a href="#binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</a></li>
|
||||||
|
<li><a href="#using-routers">Using Routers</a></li>
|
||||||
|
<li><a href="#trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</a></li>
|
||||||
|
<li><a href="#reviewing-our-work">Reviewing our work</a></li>
|
||||||
|
<li><a href="#onwards-and-upwards">Onwards and upwards</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="tutorial-6-viewsets-routers">Tutorial 6: ViewSets & Routers</h1>
|
||||||
|
<p>REST framework includes an abstraction for dealing with <code>ViewSets</code>, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.</p>
|
||||||
|
<p><code>ViewSet</code> classes are almost the same thing as <code>View</code> classes, except that they provide operations such as <code>read</code>, or <code>update</code>, and not method handlers such as <code>get</code> or <code>put</code>.</p>
|
||||||
|
<p>A <code>ViewSet</code> class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a <code>Router</code> class which handles the complexities of defining the URL conf for you.</p>
|
||||||
|
<h2 id="refactoring-to-use-viewsets">Refactoring to use ViewSets</h2>
|
||||||
|
<p>Let's take our current set of views, and refactor them into view sets.</p>
|
||||||
|
<p>First of all let's refactor our <code>UserList</code> and <code>UserDetail</code> views into a single <code>UserViewSet</code>. We can remove the two views, and replace them with a single class:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework import viewsets
|
||||||
|
|
||||||
|
class UserViewSet(viewsets.ReadOnlyModelViewSet):
|
||||||
|
"""
|
||||||
|
This viewset automatically provides `list` and `detail` actions.
|
||||||
|
"""
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>Here we've used <code>ReadOnlyModelViewSet</code> class to automatically provide the default 'read-only' operations. We're still setting the <code>queryset</code> and <code>serializer_class</code> attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.</p>
|
||||||
|
<p>Next we're going to replace the <code>SnippetList</code>, <code>SnippetDetail</code> and <code>SnippetHighlight</code> view classes. We can remove the three views, and again replace them with a single class.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from rest_framework.decorators import link
|
||||||
|
|
||||||
|
class SnippetViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
This viewset automatically provides `list`, `create`, `retrieve`,
|
||||||
|
`update` and `destroy` actions.
|
||||||
|
|
||||||
|
Additionally we also provide an extra `highlight` action.
|
||||||
|
"""
|
||||||
|
queryset = Snippet.objects.all()
|
||||||
|
serializer_class = SnippetSerializer
|
||||||
|
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
|
||||||
|
IsOwnerOrReadOnly,)
|
||||||
|
|
||||||
|
@link(renderer_classes=[renderers.StaticHTMLRenderer])
|
||||||
|
def highlight(self, request, *args, **kwargs):
|
||||||
|
snippet = self.get_object()
|
||||||
|
return Response(snippet.highlighted)
|
||||||
|
|
||||||
|
def pre_save(self, obj):
|
||||||
|
obj.owner = self.request.user
|
||||||
|
</code></pre>
|
||||||
|
<p>This time we've used the <code>ModelViewSet</code> class in order to get the complete set of default read and write operations.</p>
|
||||||
|
<p>Notice that we've also used the <code>@link</code> decorator to create a custom action, named <code>highlight</code>. This decorator can be used to add any custom endpoints that don't fit into the standard <code>create</code>/<code>update</code>/<code>delete</code> style.</p>
|
||||||
|
<p>Custom actions which use the <code>@link</code> decorator will respond to <code>GET</code> requests. We could have instead used the <code>@action</code> decorator if we wanted an action that responded to <code>POST</code> requests.</p>
|
||||||
|
<h2 id="binding-viewsets-to-urls-explicitly">Binding ViewSets to URLs explicitly</h2>
|
||||||
|
<p>The handler methods only get bound to the actions when we define the URLConf.
|
||||||
|
To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.</p>
|
||||||
|
<p>In the <code>urls.py</code> file we bind our <code>ViewSet</code> classes into a set of concrete views.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from snippets.views import SnippetViewSet, UserViewSet
|
||||||
|
from rest_framework import renderers
|
||||||
|
|
||||||
|
snippet_list = SnippetViewSet.as_view({
|
||||||
|
'get': 'list',
|
||||||
|
'post': 'create'
|
||||||
|
})
|
||||||
|
snippet_detail = SnippetViewSet.as_view({
|
||||||
|
'get': 'retrieve',
|
||||||
|
'put': 'update',
|
||||||
|
'patch': 'partial_update',
|
||||||
|
'delete': 'destroy'
|
||||||
|
})
|
||||||
|
snippet_highlight = SnippetViewSet.as_view({
|
||||||
|
'get': 'highlight'
|
||||||
|
}, renderer_classes=[renderers.StaticHTMLRenderer])
|
||||||
|
user_list = UserViewSet.as_view({
|
||||||
|
'get': 'list'
|
||||||
|
})
|
||||||
|
user_detail = UserViewSet.as_view({
|
||||||
|
'get': 'retrieve'
|
||||||
|
})
|
||||||
|
</code></pre>
|
||||||
|
<p>Notice how we're creating multiple views from each <code>ViewSet</code> class, by binding the http methods to the required action for each view.</p>
|
||||||
|
<p>Now that we've bound our resources into concrete views, that we can register the views with the URL conf as usual.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>urlpatterns = format_suffix_patterns(patterns('snippets.views',
|
||||||
|
url(r'^$', 'api_root'),
|
||||||
|
url(r'^snippets/$', snippet_list, name='snippet-list'),
|
||||||
|
url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
|
||||||
|
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
|
||||||
|
url(r'^users/$', user_list, name='user-list'),
|
||||||
|
url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
|
||||||
|
))
|
||||||
|
</code></pre>
|
||||||
|
<h2 id="using-routers">Using Routers</h2>
|
||||||
|
<p>Because we're using <code>ViewSet</code> classes rather than <code>View</code> classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a <code>Router</code> class. All we need to do is register the appropriate view sets with a router, and let it do the rest.</p>
|
||||||
|
<p>Here's our re-wired <code>urls.py</code> file.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url, include
|
||||||
|
from snippets import views
|
||||||
|
from rest_framework.routers import DefaultRouter
|
||||||
|
|
||||||
|
# Create a router and register our viewsets with it.
|
||||||
|
router = DefaultRouter()
|
||||||
|
router.register(r'snippets', views.SnippetViewSet)
|
||||||
|
router.register(r'users', views.UserViewSet)
|
||||||
|
|
||||||
|
# The API URLs are now determined automatically by the router.
|
||||||
|
# Additionally, we include the login URLs for the browseable API.
|
||||||
|
urlpatterns = patterns('',
|
||||||
|
url(r'^', include(router.urls)),
|
||||||
|
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.</p>
|
||||||
|
<p>The <code>DefaultRouter</code> class we're using also automatically creates the API root view for us, so we can now delete the <code>api_root</code> method from our <code>views</code> module.</p>
|
||||||
|
<h2 id="trade-offs-between-views-vs-viewsets">Trade-offs between views vs viewsets</h2>
|
||||||
|
<p>Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.</p>
|
||||||
|
<p>That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.</p>
|
||||||
|
<h2 id="reviewing-our-work">Reviewing our work</h2>
|
||||||
|
<p>With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.</p>
|
||||||
|
<p>We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.</p>
|
||||||
|
<p>You can review the final <a href="https://github.com/tomchristie/rest-framework-tutorial">tutorial code</a> on GitHub, or try out a live example in <a href="http://restframework.herokuapp.com/">the sandbox</a>.</p>
|
||||||
|
<h2 id="onwards-and-upwards">Onwards and upwards</h2>
|
||||||
|
<p>We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Contribute on <a href="https://github.com/tomchristie/django-rest-framework">GitHub</a> by reviewing and submitting issues, and making pull requests.</li>
|
||||||
|
<li>Join the <a href="https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework">REST framework discussion group</a>, and help build the community.</li>
|
||||||
|
<li>Follow <a href="https://twitter.com/_tomchristie">the author</a> on Twitter and say hi.</li>
|
||||||
|
</ul>
|
||||||
|
<p><strong>Now go build awesome things.</strong></p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|
385
tutorial/quickstart.html
Normal file
|
@ -0,0 +1,385 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Django REST framework - Quickstart</title>
|
||||||
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Django, API, REST, Quickstart">
|
||||||
|
<meta name="author" content="Tom Christie">
|
||||||
|
|
||||||
|
<!-- Le styles -->
|
||||||
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||||||
|
<link href="http://django-rest-framework.org/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>
|
||||||
|
</head>
|
||||||
|
<body onload="prettyPrint()" class="quickstart-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 " href="../tutorial/1-serialization.html">Next <i class="icon-arrow-right icon-white"></i></a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small " href="../index.html"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||||||
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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://django-rest-framework.org">Django REST framework</a>
|
||||||
|
<div class="nav-collapse collapse">
|
||||||
|
<ul class="nav">
|
||||||
|
<li><a href="http://django-rest-framework.org">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="http://django-rest-framework.org/tutorial/quickstart.html">Quickstart</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization.html">1 - Serialization</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses.html">2 - Requests and responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views.html">3 - Class based views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html">4 - Authentication and permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html">5 - Relationships and hyperlinked APIs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers.html">6 - Viewsets and routers</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/requests.html">Requests</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/responses.html">Responses</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/views.html">Views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views.html">Generic views</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets.html">Viewsets</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/routers.html">Routers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/parsers.html">Parsers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/renderers.html">Renderers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/serializers.html">Serializers</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/fields.html">Serializer fields</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/relations.html">Serializer relations</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/authentication.html">Authentication</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/permissions.html">Permissions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/throttling.html">Throttling</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/filtering.html">Filtering</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/pagination.html">Pagination</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation.html">Content negotiation</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes.html">Format suffixes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/reverse.html">Returning URLs</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions.html">Exceptions</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes.html">Status codes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/testing.html">Testing</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/api-guide/settings.html">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="http://django-rest-framework.org/topics/documenting-your-api.html">Documenting your API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors.html">AJAX, CSRF & CORS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements.html">Browser enhancements</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/browsable-api.html">The Browsable API</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas.html">REST, Hypermedia & HATEOAS</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement.html">2.0 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement.html">2.2 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement.html">2.3 Announcement</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/release-notes.html">Release Notes</a></li>
|
||||||
|
<li><a href="http://django-rest-framework.org/topics/credits.html">Credits</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<ul class="nav pull-right">
|
||||||
|
<!-- TODO
|
||||||
|
<li class="dropdown">
|
||||||
|
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
|
||||||
|
<ul class="dropdown-menu">
|
||||||
|
<li><a href="#">Trunk</a></li>
|
||||||
|
<li><a href="#">2.0.0</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
-->
|
||||||
|
</ul>
|
||||||
|
</div><!--/.nav-collapse -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body-content">
|
||||||
|
<div class="container-fluid">
|
||||||
|
|
||||||
|
<!-- Search Modal -->
|
||||||
|
<div id="searchModal" 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">
|
||||||
|
<!-- Custom google search -->
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
var cx = '015016005043623903336:rxraeohqk6w';
|
||||||
|
var gcse = document.createElement('script');
|
||||||
|
gcse.type = 'text/javascript';
|
||||||
|
gcse.async = true;
|
||||||
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
||||||
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
||||||
|
var s = document.getElementsByTagName('script')[0];
|
||||||
|
s.parentNode.insertBefore(gcse, s);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<gcse:search></gcse:search>
|
||||||
|
</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">
|
||||||
|
<!-- TODO
|
||||||
|
<p style="margin-top: -12px">
|
||||||
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
||||||
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
||||||
|
</p>
|
||||||
|
-->
|
||||||
|
<div id="table-of-contents">
|
||||||
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||||
|
<li class="main"><a href="#quickstart">Quickstart</a></li>
|
||||||
|
<li><a href="#project-setup">Project setup</a></li>
|
||||||
|
<li><a href="#serializers">Serializers</a></li>
|
||||||
|
<li><a href="#views">Views</a></li>
|
||||||
|
<li><a href="#urls">URLs</a></li>
|
||||||
|
<li><a href="#settings">Settings</a></li>
|
||||||
|
<li><a href="#testing-our-api">Testing our API</a></li>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
||||||
|
|
||||||
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
||||||
|
|
||||||
|
<!-- Begin MailChimp Signup Form -->
|
||||||
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
||||||
|
<style type="text/css">
|
||||||
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||||
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||||
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||||
|
</style>
|
||||||
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
||||||
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||||
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
||||||
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
||||||
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</style></div>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
|
||||||
|
<!--End mc_embed_signup-->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="main-content" class="span9">
|
||||||
|
<h1 id="quickstart">Quickstart</h1>
|
||||||
|
<p>We're going to create a simple API to allow admin users to view and edit the users and groups in the system.</p>
|
||||||
|
<h2 id="project-setup">Project setup</h2>
|
||||||
|
<p>Create a new Django project named <code>tutorial</code>, then start a new app called <code>quickstart</code>.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code># Set up a new project
|
||||||
|
django-admin.py startproject tutorial
|
||||||
|
cd tutorial
|
||||||
|
|
||||||
|
# Create a virtualenv to isolate our package dependencies locally
|
||||||
|
virtualenv env
|
||||||
|
source env/bin/activate # On Windows use `env\Scripts\activate`
|
||||||
|
|
||||||
|
# Install Django and Django REST framework into the virtualenv
|
||||||
|
pip install django
|
||||||
|
pip install djangorestframework
|
||||||
|
|
||||||
|
# Create a new app
|
||||||
|
python manage.py startapp quickstart
|
||||||
|
</code></pre>
|
||||||
|
<p>Next you'll need to get a database set up and synced. If you just want to use SQLite for now, then you'll want to edit your <code>tutorial/settings.py</code> module to include something like this:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>DATABASES = {
|
||||||
|
'default': {
|
||||||
|
'ENGINE': 'django.db.backends.sqlite3',
|
||||||
|
'NAME': 'database.sql',
|
||||||
|
'USER': '',
|
||||||
|
'PASSWORD': '',
|
||||||
|
'HOST': '',
|
||||||
|
'PORT': ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>The run <code>syncdb</code> like so:</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python manage.py syncdb
|
||||||
|
</code></pre>
|
||||||
|
<p>Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding...</p>
|
||||||
|
<h2 id="serializers">Serializers</h2>
|
||||||
|
<p>First up we're going to define some serializers in <code>quickstart/serializers.py</code> that we'll use for our data representations.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User, Group
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
|
||||||
|
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ('url', 'username', 'email', 'groups')
|
||||||
|
|
||||||
|
|
||||||
|
class GroupSerializer(serializers.HyperlinkedModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Group
|
||||||
|
fields = ('url', 'name')
|
||||||
|
</code></pre>
|
||||||
|
<p>Notice that we're using hyperlinked relations in this case, with <code>HyperlinkedModelSerializer</code>. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.</p>
|
||||||
|
<h2 id="views">Views</h2>
|
||||||
|
<p>Right, we'd better write some views then. Open <code>quickstart/views.py</code> and get typing.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User, Group
|
||||||
|
from rest_framework import viewsets
|
||||||
|
from quickstart.serializers import UserSerializer, GroupSerializer
|
||||||
|
|
||||||
|
|
||||||
|
class UserViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
API endpoint that allows users to be viewed or edited.
|
||||||
|
"""
|
||||||
|
queryset = User.objects.all()
|
||||||
|
serializer_class = UserSerializer
|
||||||
|
|
||||||
|
|
||||||
|
class GroupViewSet(viewsets.ModelViewSet):
|
||||||
|
"""
|
||||||
|
API endpoint that allows groups to be viewed or edited.
|
||||||
|
"""
|
||||||
|
queryset = Group.objects.all()
|
||||||
|
serializer_class = GroupSerializer
|
||||||
|
</code></pre>
|
||||||
|
<p>Rather than write multiple views we're grouping together all the common behavior into classes called <code>ViewSets</code>.</p>
|
||||||
|
<p>We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.</p>
|
||||||
|
<h2 id="urls">URLs</h2>
|
||||||
|
<p>Okay, now let's wire up the API URLs. On to <code>tutorial/urls.py</code>...</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>from django.conf.urls import patterns, url, include
|
||||||
|
from rest_framework import routers
|
||||||
|
from quickstart import views
|
||||||
|
|
||||||
|
router = routers.DefaultRouter()
|
||||||
|
router.register(r'users', views.UserViewSet)
|
||||||
|
router.register(r'groups', views.GroupViewSet)
|
||||||
|
|
||||||
|
# Wire up our API using automatic URL routing.
|
||||||
|
# Additionally, we include login URLs for the browseable API.
|
||||||
|
urlpatterns = patterns('',
|
||||||
|
url(r'^', include(router.urls)),
|
||||||
|
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||||
|
)
|
||||||
|
</code></pre>
|
||||||
|
<p>Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.</p>
|
||||||
|
<p>Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.</p>
|
||||||
|
<p>Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.</p>
|
||||||
|
<h2 id="settings">Settings</h2>
|
||||||
|
<p>We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in <code>tutorial/settings.py</code></p>
|
||||||
|
<pre class="prettyprint lang-py"><code>INSTALLED_APPS = (
|
||||||
|
...
|
||||||
|
'rest_framework',
|
||||||
|
)
|
||||||
|
|
||||||
|
REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
|
||||||
|
'PAGINATE_BY': 10
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Okay, we're done.</p>
|
||||||
|
<hr />
|
||||||
|
<h2 id="testing-our-api">Testing our API</h2>
|
||||||
|
<p>We're now ready to test the API we've built. Let's fire up the server from the command line.</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>python ./manage.py runserver
|
||||||
|
</code></pre>
|
||||||
|
<p>We can now access our API, both from the command-line, using tools like <code>curl</code>...</p>
|
||||||
|
<pre class="prettyprint lang-py"><code>bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
|
||||||
|
{
|
||||||
|
"count": 2,
|
||||||
|
"next": null,
|
||||||
|
"previous": null,
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"email": "admin@example.com",
|
||||||
|
"groups": [],
|
||||||
|
"url": "http://127.0.0.1:8000/users/1/",
|
||||||
|
"username": "admin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"email": "tom@example.com",
|
||||||
|
"groups": [ ],
|
||||||
|
"url": "http://127.0.0.1:8000/users/2/",
|
||||||
|
"username": "tom"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</code></pre>
|
||||||
|
<p>Or directly through the browser...</p>
|
||||||
|
<p><img alt="Quick start image" src="../img/quickstart.png" /></p>
|
||||||
|
<p>Great, that was easy!</p>
|
||||||
|
<p>If you want to get a more in depth understanding of how REST framework fits together head on over to <a href="1-serialization.html">the tutorial</a>, or start browsing the <a href="../#api-guide">API guide</a>.</p>
|
||||||
|
</div><!--/span-->
|
||||||
|
</div><!--/row-->
|
||||||
|
</div><!--/.fluid-container-->
|
||||||
|
</div><!--/.body content-->
|
||||||
|
|
||||||
|
<div id="push"></div>
|
||||||
|
</div><!--/.wrapper -->
|
||||||
|
|
||||||
|
<footer class="span12">
|
||||||
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<!-- Le javascript
|
||||||
|
================================================== -->
|
||||||
|
<!-- Placed at the end of the document so the pages load faster -->
|
||||||
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
||||||
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
||||||
|
<script>
|
||||||
|
//$('.side-nav').scrollspy()
|
||||||
|
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 to no higher than browser window
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
|
||||||
|
$(function(){
|
||||||
|
$(window).resize(function(){
|
||||||
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body></html>
|