diff options
Diffstat (limited to 'topics')
| -rw-r--r-- | topics/2.2-announcement/index.html | 10 | ||||
| -rw-r--r-- | topics/2.3-announcement/index.html | 10 | ||||
| -rw-r--r-- | topics/2.4-announcement/index.html | 12 | ||||
| -rw-r--r-- | topics/3.0-announcement/index.html | 1186 | ||||
| -rw-r--r-- | topics/ajax-csrf-cors/index.html | 10 | ||||
| -rw-r--r-- | topics/browsable-api/index.html | 42 | ||||
| -rw-r--r-- | topics/browser-enhancements/index.html | 10 | ||||
| -rw-r--r-- | topics/contributing/index.html | 11 | ||||
| -rw-r--r-- | topics/credits/index.html | 10 | ||||
| -rw-r--r-- | topics/documenting-your-api/index.html | 10 | ||||
| -rw-r--r-- | topics/kickstarter-announcement/index.html | 12 | ||||
| -rw-r--r-- | topics/release-notes/index.html | 147 | ||||
| -rw-r--r-- | topics/rest-framework-2-announcement/index.html | 10 | ||||
| -rw-r--r-- | topics/rest-hypermedia-hateoas/index.html | 18 | ||||
| -rw-r--r-- | topics/third-party-resources/index.html | 16 |
15 files changed, 1334 insertions, 180 deletions
diff --git a/topics/2.2-announcement/index.html b/topics/2.2-announcement/index.html index a088c681..16412a7b 100644 --- a/topics/2.2-announcement/index.html +++ b/topics/2.2-announcement/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -492,7 +500,7 @@ serializer.data <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/2.3-announcement/index.html b/topics/2.3-announcement/index.html index 0299adf6..84a82cb6 100644 --- a/topics/2.3-announcement/index.html +++ b/topics/2.3-announcement/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -629,7 +637,7 @@ urlpatterns = [ <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/2.4-announcement/index.html b/topics/2.4-announcement/index.html index 8d27a67e..5a7d4194 100644 --- a/topics/2.4-announcement/index.html +++ b/topics/2.4-announcement/index.html @@ -62,7 +62,7 @@ <div class="navbar-inner"> <div class="container-fluid"> <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a> - <a class="repo-link btn btn-inverse btn-small " rel="prev" href="../kickstarter-announcement"> + <a class="repo-link btn btn-inverse btn-small " rel="prev" href="../3.0-announcement"> Next <i class="icon-arrow-right icon-white"></i> </a> <a class="repo-link btn btn-inverse btn-small " rel="next" href="../2.3-announcement"> @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -515,7 +523,7 @@ The lowest supported version of Django is now 1.4.2.</p> <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/3.0-announcement/index.html b/topics/3.0-announcement/index.html new file mode 100644 index 00000000..adb1d96f --- /dev/null +++ b/topics/3.0-announcement/index.html @@ -0,0 +1,1186 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + <meta charset="utf-8"> + <title>3.0 Announcement - Django REST framework</title> + <link href="../../img/favicon.ico" rel="icon" type="image/x-icon"> + <link rel="canonical" href="http://www.django-rest-framework.org/topics/3.0-announcement/" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta name="description" content="Django, API, REST, 3.0 Announcement"> + <meta name="author" content="Tom Christie"> + + <!-- Le styles --> + <link href="../../css/prettify.css" rel="stylesheet"> + <link href="../../css/bootstrap.css" rel="stylesheet"> + <link href="../../css/bootstrap-responsive.css" rel="stylesheet"> + <link href="../../css/default.css" rel="stylesheet"> + + <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> + <!--[if lt IE 9]> + <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> + <![endif]--> + + <script type="text/javascript"> + var _gaq = _gaq || []; + _gaq.push(['_setAccount', 'UA-18852272-2']); + _gaq.push(['_trackPageview']); + + (function() { + var ga = document.createElement('script'); + ga.type = 'text/javascript'; + ga.async = true; + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(ga, s); + })(); + </script> + + <style> + span.fusion-wrap a { + display: block; + margin-top: 10px; + color: black; + } + a.fusion-poweredby { + display: block; + margin-top: 10px; + } + @media (max-width: 767px) { + div.promo { + display: none; + } + } + </style> +</head> +<body onload="prettyPrint()" class="-page"> + + <div class="wrapper"> + + <div class="navbar navbar-inverse navbar-fixed-top"> + <div class="navbar-inner"> + <div class="container-fluid"> + <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a> + <a class="repo-link btn btn-inverse btn-small " rel="prev" href="../kickstarter-announcement"> + Next <i class="icon-arrow-right icon-white"></i> + </a> + <a class="repo-link btn btn-inverse btn-small " rel="next" href="../2.4-announcement"> + <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://www.django-rest-framework.org">Django REST framework</a> + <div class="nav-collapse collapse"> + + <!-- Main navigation --> + <ul class="nav navbar-nav"> + <li ><a href="/">Home</a></li> + + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a> + <ul class="dropdown-menu"> + + <li > + <a href="../../tutorial/quickstart">Quickstart</a> + </li> + + <li > + <a href="../../tutorial/1-serialization">1 - Serialization</a> + </li> + + <li > + <a href="../../tutorial/2-requests-and-responses">2 - Requests and responses</a> + </li> + + <li > + <a href="../../tutorial/3-class-based-views">3 - Class based views</a> + </li> + + <li > + <a href="../../tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a> + </li> + + <li > + <a href="../../tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a> + </li> + + <li > + <a href="../../tutorial/6-viewsets-and-routers">6 - Viewsets and routers</a> + </li> + + </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="../../api-guide/requests">Requests</a> + </li> + + <li > + <a href="../../api-guide/responses">Responses</a> + </li> + + <li > + <a href="../../api-guide/views">Views</a> + </li> + + <li > + <a href="../../api-guide/generic-views">Generic views</a> + </li> + + <li > + <a href="../../api-guide/viewsets">Viewsets</a> + </li> + + <li > + <a href="../../api-guide/routers">Routers</a> + </li> + + <li > + <a href="../../api-guide/parsers">Parsers</a> + </li> + + <li > + <a href="../../api-guide/renderers">Renderers</a> + </li> + + <li > + <a href="../../api-guide/serializers">Serializers</a> + </li> + + <li > + <a href="../../api-guide/fields">Serializer fields</a> + </li> + + <li > + <a href="../../api-guide/relations">Serializer relations</a> + </li> + + <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > + <a href="../../api-guide/authentication">Authentication</a> + </li> + + <li > + <a href="../../api-guide/permissions">Permissions</a> + </li> + + <li > + <a href="../../api-guide/throttling">Throttling</a> + </li> + + <li > + <a href="../../api-guide/filtering">Filtering</a> + </li> + + <li > + <a href="../../api-guide/pagination">Pagination</a> + </li> + + <li > + <a href="../../api-guide/content-negotiation">Content negotiation</a> + </li> + + <li > + <a href="../../api-guide/format-suffixes">Format suffixes</a> + </li> + + <li > + <a href="../../api-guide/reverse">Returning URLs</a> + </li> + + <li > + <a href="../../api-guide/exceptions">Exceptions</a> + </li> + + <li > + <a href="../../api-guide/status-codes">Status codes</a> + </li> + + <li > + <a href="../../api-guide/testing">Testing</a> + </li> + + <li > + <a href="../../api-guide/settings">Settings</a> + </li> + + </ul> + </li> + + <li class="dropdown active"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a> + <ul class="dropdown-menu"> + + <li > + <a href="../documenting-your-api">Documenting your API</a> + </li> + + <li > + <a href="../ajax-csrf-cors">AJAX, CSRF & CORS</a> + </li> + + <li > + <a href="../browser-enhancements">Browser enhancements</a> + </li> + + <li > + <a href="../browsable-api">The Browsable API</a> + </li> + + <li > + <a href="../rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a> + </li> + + <li > + <a href="../third-party-resources">Third Party Resources</a> + </li> + + <li > + <a href="../contributing">Contributing to REST framework</a> + </li> + + <li > + <a href="../rest-framework-2-announcement">2.0 Announcement</a> + </li> + + <li > + <a href="../2.2-announcement">2.2 Announcement</a> + </li> + + <li > + <a href="../2.3-announcement">2.3 Announcement</a> + </li> + + <li > + <a href="../2.4-announcement">2.4 Announcement</a> + </li> + + <li class="active" > + <a href=".">3.0 Announcement</a> + </li> + + <li > + <a href="../kickstarter-announcement">Kickstarter Announcement</a> + </li> + + <li > + <a href="../release-notes">Release Notes</a> + </li> + + <li > + <a href="../credits">Credits</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-30">REST framework 3.0</a> + </li> + + + <li> + <a href="#new-features">New features</a> + </li> + + <li> + <a href="#request-objects">Request objects</a> + </li> + + <li> + <a href="#serializers">Serializers</a> + </li> + + <li> + <a href="#serializer-fields">Serializer fields</a> + </li> + + <li> + <a href="#generic-views">Generic views</a> + </li> + + <li> + <a href="#the-metadata-api">The metadata API</a> + </li> + + <li> + <a href="#serializers-as-html-forms">Serializers as HTML forms</a> + </li> + + <li> + <a href="#api-style">API style</a> + </li> + + <li> + <a href="#miscellaneous-notes">Miscellaneous notes</a> + </li> + + <li> + <a href="#whats-coming-next">What's coming next</a> + </li> + + + + + + + </ul> + + </div> + </div> + + <div id="main-content" class="span9"> + + + <h1 id="rest-framework-30">REST framework 3.0</h1> +<p>The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.</p> +<p>This release is incremental in nature. There <em>are</em> some breaking API changes, and upgrading <em>will</em> require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.</p> +<p>The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.</p> +<p>3.0 is the first of three releases that have been funded by our recent <a href="http://kickstarter.com/projects/tomchristie/django-rest-framework-3">Kickstarter campaign</a>.</p> +<p>As ever, a huge thank you to our many <a href="http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors">wonderful sponsors</a>. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.</p> +<hr /> +<h2 id="new-features">New features</h2> +<p>Notable features of this new release include:</p> +<ul> +<li>Printable representations on serializers that allow you to inspect exactly what fields are present on the instance.</li> +<li>Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit <code>ModelSerializer</code> class and the explicit <code>Serializer</code> class.</li> +<li>A new <code>BaseSerializer</code> class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.</li> +<li>A cleaner fields API including new classes such as <code>ListField</code> and <code>MultipleChoiceField</code>.</li> +<li><a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py">Super simple default implementations</a> for the generic views.</li> +<li>Support for overriding how validation errors are handled by your API.</li> +<li>A metadata API that allows you to customize how <code>OPTIONS</code> requests are handled by your API.</li> +<li>A more compact JSON output with unicode style encoding turned on by default.</li> +<li>Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.</li> +</ul> +<p>Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two <a href="https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3">Kickstarter stretch goals</a> - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.</p> +<p>Below is an in-depth guide to the API changes and migration notes for 3.0.</p> +<hr /> +<h2 id="request-objects">Request objects</h2> +<h4 id="the-data-and-query_params-properties">The <code>.data</code> and <code>.query_params</code> properties.</h4> +<p>The usage of <code>request.DATA</code> and <code>request.FILES</code> is now pending deprecation in favor of a single <code>request.data</code> attribute that contains <em>all</em> the parsed data.</p> +<p>Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.</p> +<p>You may now pass all the request data to a serializer class in a single argument:</p> +<pre><code># Do this... +ExampleSerializer(data=request.data) +</code></pre> +<p>Instead of passing the files argument separately:</p> +<pre><code># Don't do this... +ExampleSerializer(data=request.DATA, files=request.FILES) +</code></pre> +<p>The usage of <code>request.QUERY_PARAMS</code> is now pending deprecation in favor of the lowercased <code>request.query_params</code>.</p> +<hr /> +<h2 id="serializers">Serializers</h2> +<h4 id="single-step-object-creation">Single-step object creation.</h4> +<p>Previously the serializers used a two-step object creation, as follows:</p> +<ol> +<li>Validating the data would create an object instance. This instance would be available as <code>serializer.object</code>.</li> +<li>Calling <code>serializer.save()</code> would then save the object instance to the database.</li> +</ol> +<p>This style is in-line with how the <code>ModelForm</code> class works in Django, but is problematic for a number of reasons:</p> +<ul> +<li>Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when <code>.save()</code> is called.</li> +<li>Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. <code>ExampleModel.objects.create(...)</code>. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.</li> +<li>The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?</li> +</ul> +<p>We now use single-step object creation, like so:</p> +<ol> +<li>Validating the data makes the cleaned data available as <code>serializer.validated_data</code>.</li> +<li>Calling <code>serializer.save()</code> then saves and returns the new object instance.</li> +</ol> +<p>The resulting API changes are further detailed below.</p> +<h4 id="the-create-and-update-methods">The <code>.create()</code> and <code>.update()</code> methods.</h4> +<p>The <code>.restore_object()</code> method is now replaced with two separate methods, <code>.create()</code> and <code>.update()</code>.</p> +<p>These methods also replace the optional <code>.save_object()</code> method, which no longer exists.</p> +<p>When using the <code>.create()</code> and <code>.update()</code> methods you should both create <em>and save</em> the object instance. This is in contrast to the previous <code>.restore_object()</code> behavior that would instantiate the object but not save it.</p> +<p>The following example from the tutorial previously used <code>restore_object()</code> to handle both creating and updating object instances.</p> +<pre><code>def restore_object(self, attrs, instance=None): + 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>This would now be split out into two separate methods.</p> +<pre><code>def update(self, instance, validated_data): + instance.title = validated_data.get('title', instance.title) + instance.code = validated_data.get('code', instance.code) + instance.linenos = validated_data.get('linenos', instance.linenos) + instance.language = validated_data.get('language', instance.language) + instance.style = validated_data.get('style', instance.style) + instance.save() + return instance + +def create(self, validated_data): + return Snippet.objects.create(**validated_data) +</code></pre> +<p>Note that these methods should return the newly created object instance.</p> +<h4 id="use-validated_data-instead-of-object">Use <code>.validated_data</code> instead of <code>.object</code>.</h4> +<p>You must now use the <code>.validated_data</code> attribute if you need to inspect the data before saving, rather than using the <code>.object</code> attribute, which no longer exists.</p> +<p>For example the following code <em>is no longer valid</em>:</p> +<pre><code>if serializer.is_valid(): + name = serializer.object.name # Inspect validated field data. + logging.info('Creating ticket "%s"' % name) + serializer.object.user = request.user # Include the user when saving. + serializer.save() +</code></pre> +<p>Instead of using <code>.object</code> to inspect a partially constructed instance, you would now use <code>.validated_data</code> to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the <code>.save()</code> method as keyword arguments.</p> +<p>The corresponding code would now look like this:</p> +<pre><code>if serializer.is_valid(): + name = serializer.validated_data['name'] # Inspect validated field data. + logging.info('Creating ticket "%s"' % name) + serializer.save(user=request.user) # Include the user when saving. +</code></pre> +<h4 id="using-is_validraise_exceptiontrue">Using <code>.is_valid(raise_exception=True)</code></h4> +<p>The <code>.is_valid()</code> method now takes an optional boolean flag, <code>raise_exception</code>.</p> +<p>Calling <code>.is_valid(raise_exception=True)</code> will cause a <code>ValidationError</code> to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.</p> +<p>The handling and formatting of error responses may be altered globally by using the <code>EXCEPTION_HANDLER</code> settings key.</p> +<p>This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.</p> +<h4 id="using-serializersvalidationerror">Using <code>serializers.ValidationError</code>.</h4> +<p>Previously <code>serializers.ValidationError</code> error was simply a synonym for <code>django.core.exceptions.ValidationError</code>. This has now been altered so that it inherits from the standard <code>APIException</code> base class.</p> +<p>The reason behind this is that Django's <code>ValidationError</code> class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.</p> +<p>For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the <code>serializers.ValidationError</code> exception class, and not Django's built-in exception.</p> +<p>We strongly recommend that you use the namespaced import style of <code>import serializers</code> and not <code>from serializers import ValidationError</code> in order to avoid any potential confusion.</p> +<h4 id="change-to-validate_field_name">Change to <code>validate_<field_name></code>.</h4> +<p>The <code>validate_<field_name></code> method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:</p> +<pre><code>def validate_score(self, attrs, source): + if attrs['score'] % 10 != 0: + raise serializers.ValidationError('This field should be a multiple of ten.') + return attrs +</code></pre> +<p>This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.</p> +<pre><code>def validate_score(self, value): + if value % 10 != 0: + raise serializers.ValidationError('This field should be a multiple of ten.') + return value +</code></pre> +<p>Any ad-hoc validation that applies to more than one field should go in the <code>.validate(self, attrs)</code> method as usual.</p> +<p>Because <code>.validate_<field_name></code> would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use <code>.validate()</code> instead.</p> +<p>You can either return <code>non_field_errors</code> from the validate method by raising a simple <code>ValidationError</code></p> +<pre><code>def validate(self, attrs): + # serializer.errors == {'non_field_errors': ['A non field error']} + raise serializers.ValidationError('A non field error') +</code></pre> +<p>Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the <code>ValidationError</code>, like so:</p> +<pre><code>def validate(self, attrs): + # serializer.errors == {'my_field': ['A field error']} + raise serializers.ValidationError({'my_field': 'A field error'}) +</code></pre> +<p>This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.</p> +<h4 id="removal-of-transform_field_name">Removal of <code>transform_<field_name></code>.</h4> +<p>The under-used <code>transform_<field_name></code> on serializer classes is no longer provided. Instead you should just override <code>to_representation()</code> if you need to apply any modifications to the representation style.</p> +<p>For example:</p> +<pre><code>def to_representation(self, instance): + ret = super(UserSerializer, self).to_representation(instance) + ret['username'] = ret['username'].lower() + return ret +</code></pre> +<p>Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.</p> +<p>If you absolutely need to preserve <code>transform_<field_name></code> behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:</p> +<pre><code>class BaseModelSerializer(ModelSerializer): + """ + A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior. + """ + def to_representation(self, instance): + ret = super(BaseModelSerializer, self).to_representation(instance) + for key, value in ret.items(): + method = getattr(self, 'transform_' + key, None) + if method is not None: + ret[key] = method(value) + return ret +</code></pre> +<h4 id="differences-between-modelserializer-validation-and-modelform">Differences between ModelSerializer validation and ModelForm.</h4> +<p>This change also means that we no longer use the <code>.full_clean()</code> method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on <code>ModelSerializer</code> classes that can't also be easily replicated on regular <code>Serializer</code> classes.</p> +<p>For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.</p> +<p>The one difference that you do need to note is that the <code>.clean()</code> method will not be called as part of serializer validation, as it would be if using a <code>ModelForm</code>. Use the serializer <code>.validate()</code> method to perform a final validation step on incoming data where required.</p> +<p>There may be some cases where you really do need to keep validation logic in the model <code>.clean()</code> method, and cannot instead separate it into the serializer <code>.validate()</code>. You can do so by explicitly instantiating a model instance in the <code>.validate()</code> method.</p> +<pre><code>def validate(self, attrs): + instance = ExampleModel(**attrs) + instance.clean() + return attrs +</code></pre> +<p>Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.</p> +<h4 id="writable-nested-serialization">Writable nested serialization.</h4> +<p>REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:</p> +<ul> +<li>There can be complex dependencies involved in order of saving multiple related model instances.</li> +<li>It's unclear what behavior the user should expect when related models are passed <code>None</code> data.</li> +<li>It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.</li> +</ul> +<p>Using the <code>depth</code> option on <code>ModelSerializer</code> will now create <strong>read-only nested serializers</strong> by default.</p> +<p>If you try to use a writable nested serializer without writing a custom <code>create()</code> and/or <code>update()</code> method you'll see an assertion error when you attempt to save the serializer. For example:</p> +<pre><code>>>> class ProfileSerializer(serializers.ModelSerializer): +>>> class Meta: +>>> model = Profile +>>> fields = ('address', 'phone') +>>> +>>> class UserSerializer(serializers.ModelSerializer): +>>> profile = ProfileSerializer() +>>> class Meta: +>>> model = User +>>> fields = ('username', 'email', 'profile') +>>> +>>> data = { +>>> 'username': 'lizzy', +>>> 'email': 'lizzy@example.com', +>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'} +>>> } +>>> +>>> serializer = UserSerializer(data=data) +>>> serializer.save() +AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields. +</code></pre> +<p>To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the <code>create()</code> and/or <code>update()</code> methods explicitly.</p> +<pre><code>class UserSerializer(serializers.ModelSerializer): + profile = ProfileSerializer() + + class Meta: + model = User + fields = ('username', 'email', 'profile') + + def create(self, validated_data): + profile_data = validated_data.pop('profile') + user = User.objects.create(**validated_data) + Profile.objects.create(user=user, **profile_data) + return user +</code></pre> +<p>The single-step object creation makes this far simpler and more obvious than the previous <code>.restore_object()</code> behavior.</p> +<h4 id="printable-serializer-representations">Printable serializer representations.</h4> +<p>Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.</p> +<p>For instance, given the following example model:</p> +<pre><code>class LocationRating(models.Model): + location = models.CharField(max_length=100) + rating = models.IntegerField() + created_by = models.ForeignKey(User) +</code></pre> +<p>Let's create a simple <code>ModelSerializer</code> class corresponding to the <code>LocationRating</code> model.</p> +<pre><code>class LocationRatingSerializer(serializer.ModelSerializer): + class Meta: + model = LocationRating +</code></pre> +<p>We can now inspect the serializer representation in the Django shell, using <code>python manage.py shell</code>...</p> +<pre><code>>>> serializer = LocationRatingSerializer() +>>> print(serializer) # Or use `print serializer` in Python 2.x +LocationRatingSerializer(): + id = IntegerField(label='ID', read_only=True) + location = CharField(max_length=100) + rating = IntegerField() + created_by = PrimaryKeyRelatedField(queryset=User.objects.all()) +</code></pre> +<h4 id="the-extra_kwargs-option">The <code>extra_kwargs</code> option.</h4> +<p>The <code>write_only_fields</code> option on <code>ModelSerializer</code> has been moved to <code>PendingDeprecation</code> and replaced with a more generic <code>extra_kwargs</code>.</p> +<pre><code>class MySerializer(serializer.ModelSerializer): + class Meta: + model = MyModel + fields = ('id', 'email', 'notes', 'is_admin') + extra_kwargs = { + 'is_admin': {'write_only': True} + } +</code></pre> +<p>Alternatively, specify the field explicitly on the serializer class:</p> +<pre><code>class MySerializer(serializer.ModelSerializer): + is_admin = serializers.BooleanField(write_only=True) + + class Meta: + model = MyModel + fields = ('id', 'email', 'notes', 'is_admin') +</code></pre> +<p>The <code>read_only_fields</code> option remains as a convenient shortcut for the more common case.</p> +<h4 id="changes-to-hyperlinkedmodelserializer">Changes to <code>HyperlinkedModelSerializer</code>.</h4> +<p>The <code>view_name</code> and <code>lookup_field</code> options have been moved to <code>PendingDeprecation</code>. They are no longer required, as you can use the <code>extra_kwargs</code> argument instead:</p> +<pre><code>class MySerializer(serializer.HyperlinkedModelSerializer): + class Meta: + model = MyModel + fields = ('url', 'email', 'notes', 'is_admin') + extra_kwargs = { + 'url': {'lookup_field': 'uuid'} + } +</code></pre> +<p>Alternatively, specify the field explicitly on the serializer class:</p> +<pre><code>class MySerializer(serializer.HyperlinkedModelSerializer): + url = serializers.HyperlinkedIdentityField( + view_name='mymodel-detail', + lookup_field='uuid' + ) + + class Meta: + model = MyModel + fields = ('url', 'email', 'notes', 'is_admin') +</code></pre> +<h4 id="fields-for-model-methods-and-properties">Fields for model methods and properties.</h4> +<p>With <code>ModelSerializer</code> you can now specify field names in the <code>fields</code> option that refer to model methods or properties. For example, suppose you have the following model:</p> +<pre><code>class Invitation(models.Model): + created = models.DateTimeField() + to_email = models.EmailField() + message = models.CharField(max_length=1000) + + def expiry_date(self): + return self.created + datetime.timedelta(days=30) +</code></pre> +<p>You can include <code>expiry_date</code> as a field option on a <code>ModelSerializer</code> class.</p> +<pre><code>class InvitationSerializer(serializers.ModelSerializer): + class Meta: + model = Invitation + fields = ('to_email', 'message', 'expiry_date') +</code></pre> +<p>These fields will be mapped to <code>serializers.ReadOnlyField()</code> instances.</p> +<pre><code>>>> serializer = InvitationSerializer() +>>> print repr(serializer) +InvitationSerializer(): + to_email = EmailField(max_length=75) + message = CharField(max_length=1000) + expiry_date = ReadOnlyField() +</code></pre> +<h4 id="the-listserializer-class">The <code>ListSerializer</code> class.</h4> +<p>The <code>ListSerializer</code> class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.</p> +<pre><code>class MultipleUserSerializer(ListSerializer): + child = UserSerializer() +</code></pre> +<p>You can also still use the <code>many=True</code> argument to serializer classes. It's worth noting that <code>many=True</code> argument transparently creates a <code>ListSerializer</code> instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.</p> +<p>You will typically want to <em>continue to use the existing <code>many=True</code> flag</em> rather than declaring <code>ListSerializer</code> classes explicitly, but declaring the classes explicitly can be useful if you need to write custom <code>create</code> or <code>update</code> methods for bulk updates, or provide for other custom behavior.</p> +<p>See also the new <code>ListField</code> class, which validates input in the same way, but does not include the serializer interfaces of <code>.is_valid()</code>, <code>.data</code>, <code>.save()</code> and so on.</p> +<h4 id="the-baseserializer-class">The <code>BaseSerializer</code> class.</h4> +<p>REST framework now includes a simple <code>BaseSerializer</code> class that can be used to easily support alternative serialization and deserialization styles.</p> +<p>This class implements the same basic API as the <code>Serializer</code> class:</p> +<ul> +<li><code>.data</code> - Returns the outgoing primitive representation.</li> +<li><code>.is_valid()</code> - Deserializes and validates incoming data.</li> +<li><code>.validated_data</code> - Returns the validated incoming data.</li> +<li><code>.errors</code> - Returns an errors during validation.</li> +<li><code>.save()</code> - Persists the validated data into an object instance.</li> +</ul> +<p>There are four methods that can be overridden, depending on what functionality you want the serializer class to support:</p> +<ul> +<li><code>.to_representation()</code> - Override this to support serialization, for read operations.</li> +<li><code>.to_internal_value()</code> - Override this to support deserialization, for write operations.</li> +<li><code>.create()</code> and <code>.update()</code> - Override either or both of these to support saving instances.</li> +</ul> +<p>Because this class provides the same interface as the <code>Serializer</code> class, you can use it with the existing generic class based views exactly as you would for a regular <code>Serializer</code> or <code>ModelSerializer</code>.</p> +<p>The only difference you'll notice when doing so is the <code>BaseSerializer</code> classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.</p> +<h5 id="read-only-baseserializer-classes">Read-only <code>BaseSerializer</code> classes.</h5> +<p>To implement a read-only serializer using the <code>BaseSerializer</code> class, we just need to override the <code>.to_representation()</code> method. Let's take a look at an example using a simple Django model:</p> +<pre><code>class HighScore(models.Model): + created = models.DateTimeField(auto_now_add=True) + player_name = models.CharField(max_length=10) + score = models.IntegerField() +</code></pre> +<p>It's simple to create a read-only serializer for converting <code>HighScore</code> instances into primitive data types.</p> +<pre><code>class HighScoreSerializer(serializers.BaseSerializer): + def to_representation(self, obj): + return { + 'score': obj.score, + 'player_name': obj.player_name + } +</code></pre> +<p>We can now use this class to serialize single <code>HighScore</code> instances:</p> +<pre><code>@api_view(['GET']) +def high_score(request, pk): + instance = HighScore.objects.get(pk=pk) + serializer = HighScoreSerializer(instance) + return Response(serializer.data) +</code></pre> +<p>Or use it to serialize multiple instances:</p> +<pre><code>@api_view(['GET']) +def all_high_scores(request): + queryset = HighScore.objects.order_by('-score') + serializer = HighScoreSerializer(queryset, many=True) + return Response(serializer.data) +</code></pre> +<h5 id="read-write-baseserializer-classes">Read-write <code>BaseSerializer</code> classes.</h5> +<p>To create a read-write serializer we first need to implement a <code>.to_internal_value()</code> method. This method returns the validated values that will be used to construct the object instance, and may raise a <code>ValidationError</code> if the supplied data is in an incorrect format.</p> +<p>Once you've implemented <code>.to_internal_value()</code>, the basic validation API will be available on the serializer, and you will be able to use <code>.is_valid()</code>, <code>.validated_data</code> and <code>.errors</code>.</p> +<p>If you want to also support <code>.save()</code> you'll need to also implement either or both of the <code>.create()</code> and <code>.update()</code> methods.</p> +<p>Here's a complete example of our previous <code>HighScoreSerializer</code>, that's been updated to support both read and write operations.</p> +<pre><code>class HighScoreSerializer(serializers.BaseSerializer): + def to_internal_value(self, data): + score = data.get('score') + player_name = data.get('player_name') + + # Perform the data validation. + if not score: + raise ValidationError({ + 'score': 'This field is required.' + }) + if not player_name: + raise ValidationError({ + 'player_name': 'This field is required.' + }) + if len(player_name) > 10: + raise ValidationError({ + 'player_name': 'May not be more than 10 characters.' + }) + + # Return the validated values. This will be available as + # the `.validated_data` property. + return { + 'score': int(score), + 'player_name': player_name + } + + def to_representation(self, obj): + return { + 'score': obj.score, + 'player_name': obj.player_name + } + + def create(self, validated_data): + return HighScore.objects.create(**validated_data) +</code></pre> +<h4 id="creating-new-generic-serializers-with-baseserializer">Creating new generic serializers with <code>BaseSerializer</code>.</h4> +<p>The <code>BaseSerializer</code> class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.</p> +<p>The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.</p> +<pre><code>class ObjectSerializer(serializers.BaseSerializer): + """ + A read-only serializer that coerces arbitrary complex objects + into primitive representations. + """ + def to_representation(self, obj): + for attribute_name in dir(obj): + attribute = getattr(obj, attribute_name) + if attribute_name('_'): + # Ignore private attributes. + pass + elif hasattr(attribute, '__call__'): + # Ignore methods and other callables. + pass + elif isinstance(attribute, (str, int, bool, float, type(None))): + # Primitive types can be passed through unmodified. + output[attribute_name] = attribute + elif isinstance(attribute, list): + # Recursively deal with items in lists. + output[attribute_name] = [ + self.to_representation(item) for item in attribute + ] + elif isinstance(attribute, dict): + # Recursively deal with items in dictionaries. + output[attribute_name] = { + str(key): self.to_representation(value) + for key, value in attribute.items() + } + else: + # Force anything else to its string representation. + output[attribute_name] = str(attribute) +</code></pre> +<hr /> +<h2 id="serializer-fields">Serializer fields</h2> +<h4 id="the-field-and-readonly-field-classes">The <code>Field</code> and <code>ReadOnly</code> field classes.</h4> +<p>There are some minor tweaks to the field base classes.</p> +<p>Previously we had these two base classes:</p> +<ul> +<li><code>Field</code> as the base class for read-only fields. A default implementation was included for serializing data.</li> +<li><code>WritableField</code> as the base class for read-write fields.</li> +</ul> +<p>We now use the following:</p> +<ul> +<li><code>Field</code> is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.</li> +<li><code>ReadOnlyField</code> is a concrete implementation for read-only fields that simply returns the attribute value without modification.</li> +</ul> +<h4 id="the-required-allow_none-allow_blank-and-default-arguments">The <code>required</code>, <code>allow_none</code>, <code>allow_blank</code> and <code>default</code> arguments.</h4> +<p>REST framework now has more explicit and clear control over validating empty values for fields.</p> +<p>Previously the meaning of the <code>required=False</code> keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be <code>None</code> or the empty string.</p> +<p>We now have a better separation, with separate <code>required</code>, <code>allow_none</code> and <code>allow_blank</code> arguments.</p> +<p>The following set of arguments are used to control validation of empty values:</p> +<ul> +<li><code>required=False</code>: The value does not need to be present in the input, and will not be passed to <code>.create()</code> or <code>.update()</code> if it is not seen.</li> +<li><code>default=<value></code>: The value does not need to be present in the input, and a default value will be passed to <code>.create()</code> or <code>.update()</code> if it is not seen.</li> +<li><code>allow_none=True</code>: <code>None</code> is a valid input.</li> +<li><code>allow_blank=True</code>: <code>''</code> is valid input. For <code>CharField</code> and subclasses only.</li> +</ul> +<p>Typically you'll want to use <code>required=False</code> if the corresponding model field has a default value, and additionally set either <code>allow_none=True</code> or <code>allow_blank=True</code> if required.</p> +<p>The <code>default</code> argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the <code>required</code> argument when a default is specified, and doing so will result in an error.</p> +<h4 id="coercing-output-types">Coercing output types.</h4> +<p>The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an <code>IntegerField</code> would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.</p> +<h4 id="removal-of-validate">Removal of <code>.validate()</code>.</h4> +<p>The <code>.validate()</code> method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override <code>to_internal_value()</code>.</p> +<pre><code>class UppercaseCharField(serializers.CharField): + def to_internal_value(self, data): + value = super(UppercaseCharField, self).to_internal_value(data) + if value != value.upper(): + raise serializers.ValidationError('The input should be uppercase only.') + return value +</code></pre> +<p>Previously validation errors could be raised in either <code>.to_native()</code> or <code>.validate()</code>, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.</p> +<h4 id="the-listfield-class">The <code>ListField</code> class.</h4> +<p>The <code>ListField</code> class has now been added. This field validates list input. It takes a <code>child</code> keyword argument which is used to specify the field used to validate each item in the list. For example:</p> +<pre><code>scores = ListField(child=IntegerField(min_value=0, max_value=100)) +</code></pre> +<p>You can also use a declarative style to create new subclasses of <code>ListField</code>, like this:</p> +<pre><code>class ScoresField(ListField): + child = IntegerField(min_value=0, max_value=100) +</code></pre> +<p>We can now use the <code>ScoresField</code> class inside another serializer:</p> +<pre><code>scores = ScoresField() +</code></pre> +<p>See also the new <code>ListSerializer</code> class, which validates input in the same way, but also includes the serializer interfaces of <code>.is_valid()</code>, <code>.data</code>, <code>.save()</code> and so on.</p> +<h4 id="the-choicefield-class-may-now-accept-a-flat-list">The <code>ChoiceField</code> class may now accept a flat list.</h4> +<p>The <code>ChoiceField</code> class may now accept a list of choices in addition to the existing style of using a list of pairs of <code>(name, display_value)</code>. The following is now valid:</p> +<pre><code>color = ChoiceField(choices=['red', 'green', 'blue']) +</code></pre> +<h4 id="the-multiplechoicefield-class">The <code>MultipleChoiceField</code> class.</h4> +<p>The <code>MultipleChoiceField</code> class has been added. This field acts like <code>ChoiceField</code>, but returns a set, which may include none, one or many of the valid choices.</p> +<h4 id="changes-to-the-custom-field-api">Changes to the custom field API.</h4> +<p>The <code>from_native(self, value)</code> and <code>to_native(self, data)</code> method names have been replaced with the more obviously named <code>to_internal_value(self, data)</code> and <code>to_representation(self, value)</code>.</p> +<p>The <code>field_from_native()</code> and <code>field_to_native()</code> methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...</p> +<pre><code>def field_to_native(self, obj, field_name): + """A custom read-only field that returns the class name.""" + return obj.__class__.__name__ +</code></pre> +<p>Now if you need to access the entire object you'll instead need to override one or both of the following:</p> +<ul> +<li>Use <code>get_attribute</code> to modify the attribute value passed to <code>to_representation()</code>.</li> +<li>Use <code>get_value</code> to modify the data value passed <code>to_internal_value()</code>.</li> +</ul> +<p>For example:</p> +<pre><code>def get_attribute(self, obj): + # Pass the entire object through to `to_representation()`, + # instead of the standard attribute lookup. + return obj + +def to_representation(self, value): + return value.__class__.__name__ +</code></pre> +<h4 id="explicit-queryset-required-on-relational-fields">Explicit <code>queryset</code> required on relational fields.</h4> +<p>Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a <code>ModelSerializer</code>.</p> +<p>This code <em>would be valid</em> in <code>2.4.3</code>:</p> +<pre><code>class AccountSerializer(serializers.ModelSerializer): + organizations = serializers.SlugRelatedField(slug_field='name') + + class Meta: + model = Account +</code></pre> +<p>However this code <em>would not be valid</em> in <code>2.4.3</code>:</p> +<pre><code># Missing `queryset` +class AccountSerializer(serializers.Serializer): + organizations = serializers.SlugRelatedField(slug_field='name') + + def restore_object(self, attrs, instance=None): + # ... +</code></pre> +<p>The queryset argument is now always required for writable relational fields. +This removes some magic and makes it easier and more obvious to move between implicit <code>ModelSerializer</code> classes and explicit <code>Serializer</code> classes.</p> +<pre><code>class AccountSerializer(serializers.ModelSerializer): + organizations = serializers.SlugRelatedField( + slug_field='name', + queryset=Organization.objects.all() + ) + + class Meta: + model = Account +</code></pre> +<p>The <code>queryset</code> argument is only ever required for writable fields, and is not required or valid for fields with <code>read_only=True</code>.</p> +<h4 id="optional-argument-to-serializermethodfield">Optional argument to <code>SerializerMethodField</code>.</h4> +<p>The argument to <code>SerializerMethodField</code> is now optional, and defaults to <code>get_<field_name></code>. For example the following is valid:</p> +<pre><code>class AccountSerializer(serializers.Serializer): + # `method_name='get_billing_details'` by default. + billing_details = serializers.SerializerMethodField() + + def get_billing_details(self, account): + return calculate_billing(account) +</code></pre> +<p>In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code <em>will raise an error</em>:</p> +<pre><code>billing_details = serializers.SerializerMethodField('get_billing_details') +</code></pre> +<h4 id="enforcing-consistent-source-usage">Enforcing consistent <code>source</code> usage.</h4> +<p>I've see several codebases that unnecessarily include the <code>source</code> argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that <code>source</code> is usually not required.</p> +<p>The following usage will <em>now raise an error</em>:</p> +<pre><code>email = serializers.EmailField(source='email') +</code></pre> +<h4 id="the-uniquevalidator-and-uniquetogethervalidator-classes">The <code>UniqueValidator</code> and <code>UniqueTogetherValidator</code> classes.</h4> +<p>REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit <code>Serializer</code> class instead of using <code>ModelSerializer</code>.</p> +<p>The <code>UniqueValidator</code> should be applied to a serializer field, and takes a single <code>queryset</code> argument.</p> +<pre><code>from rest_framework import serializers +from rest_framework.validators import UniqueValidator + +class OrganizationSerializer(serializers.Serializer): + url = serializers.HyperlinkedIdentityField(view_name='organization_detail') + created = serializers.DateTimeField(read_only=True) + name = serializers.CharField( + max_length=100, + validators=UniqueValidator(queryset=Organization.objects.all()) + ) +</code></pre> +<p>The <code>UniqueTogetherValidator</code> should be applied to a serializer, and takes a <code>queryset</code> argument and a <code>fields</code> argument which should be a list or tuple of field names.</p> +<pre><code>class RaceResultSerializer(serializers.Serializer): + category = serializers.ChoiceField(['5k', '10k']) + position = serializers.IntegerField() + name = serializers.CharField(max_length=100) + + class Meta: + validators = [UniqueTogetherValidator( + queryset=RaceResult.objects.all(), + fields=('category', 'position') + )] +</code></pre> +<h4 id="the-uniquefordatevalidator-classes">The <code>UniqueForDateValidator</code> classes.</h4> +<p>REST framework also now includes explicit validator classes for validating the <code>unique_for_date</code>, <code>unique_for_month</code>, and <code>unique_for_year</code> model field constraints. These are used internally instead of calling into <code>Model.full_clean()</code>.</p> +<p>These classes are documented in the <a href="../../api-guide/validators">Validators</a> section of the documentation.</p> +<hr /> +<h2 id="generic-views">Generic views</h2> +<h4 id="simplification-of-view-logic">Simplification of view logic.</h4> +<p>The view logic for the default method handlers has been significantly simplified, due to the new serializers API.</p> +<h4 id="changes-to-prepost-save-hooks">Changes to pre/post save hooks.</h4> +<p>The <code>pre_save</code> and <code>post_save</code> hooks no longer exist, but are replaced with <code>perform_create(self, serializer)</code> and <code>perform_update(self, serializer)</code>.</p> +<p>These methods should save the object instance by calling <code>serializer.save()</code>, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.</p> +<p>For example:</p> +<pre><code>def perform_create(self, serializer): + # Include the owner attribute directly, rather than from request data. + instance = serializer.save(owner=self.request.user) + # Perform a custom post-save action. + send_email(instance.to_email, instance.message) +</code></pre> +<p>The <code>pre_delete</code> and <code>post_delete</code> hooks no longer exist, and are replaced with <code>.perform_destroy(self, instance)</code>, which should delete the instance and perform any custom actions.</p> +<pre><code>def perform_destroy(self, instance): + # Perform a custom pre-delete action. + send_deletion_alert(user=instance.created_by, deleted=instance) + # Delete the object instance. + instance.delete() +</code></pre> +<h4 id="removal-of-view-attributes">Removal of view attributes.</h4> +<p>The <code>.object</code> and <code>.object_list</code> attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.</p> +<p>I would personally recommend that developers treat view instances as immutable objects in their application code.</p> +<h4 id="put-as-create">PUT as create.</h4> +<p>Allowing <code>PUT</code> as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning <code>404</code> responses.</p> +<p>Both styles "<code>PUT</code> as 404" and "<code>PUT</code> as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.</p> +<p>If you need to restore the previous behavior you may want to include <a href="https://gist.github.com/tomchristie/a2ace4577eff2c603b1b">this <code>AllowPUTAsCreateMixin</code> class</a> as a mixin to your views.</p> +<h4 id="customizing-error-responses">Customizing error responses.</h4> +<p>The generic views now raise <code>ValidationFailed</code> exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a <code>400 Bad Request</code> response directly.</p> +<p>This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.</p> +<hr /> +<h2 id="the-metadata-api">The metadata API</h2> +<p>Behavior for dealing with <code>OPTIONS</code> requests was previously built directly into the class based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.</p> +<p>This makes it far easier to use a different style for <code>OPTIONS</code> responses throughout your API, and makes it possible to create third-party metadata policies.</p> +<hr /> +<h2 id="serializers-as-html-forms">Serializers as HTML forms</h2> +<p>REST framework 3.0 includes templated HTML form rendering for serializers.</p> +<p>This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.</p> +<p>Significant changes that you do need to be aware of include:</p> +<ul> +<li>Nested HTML forms are now supported, for example, a <code>UserSerializer</code> with a nested <code>ProfileSerializer</code> will now render a nested <code>fieldset</code> when used in the browsable API.</li> +<li>Nested lists of HTML forms are not yet supported, but are planned for 3.1.</li> +<li>Because we now use templated HTML form generation, <strong>the <code>widget</code> option is no longer available for serializer fields</strong>. You can instead control the template that is used for a given field, by using the <code>style</code> dictionary.</li> +</ul> +<h4 id="the-style-keyword-argument-for-serializer-fields">The <code>style</code> keyword argument for serializer fields.</h4> +<p>The <code>style</code> keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the <code>HTMLFormRenderer</code> uses the <code>base_template</code> key to determine which template to render the field with.</p> +<p>For example, to use a <code>textarea</code> control instead of the default <code>input</code> control, you would use the following…</p> +<pre><code>additional_notes = serializers.CharField( + style={'base_template': 'text_area.html'} +) +</code></pre> +<p>Similarly, to use a radio button control instead of the default <code>select</code> control, you would use the following…</p> +<pre><code>color_channel = serializers.ChoiceField( + choices=['red', 'blue', 'green'], + style={'base_template': 'radio.html'} +) +</code></pre> +<p>This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.</p> +<hr /> +<h2 id="api-style">API style</h2> +<p>There are some improvements in the default style we use in our API responses.</p> +<h4 id="unicode-json-by-default">Unicode JSON by default.</h4> +<p>Unicode JSON is now the default. The <code>UnicodeJSONRenderer</code> class no longer exists, and the <code>UNICODE_JSON</code> setting has been added. To revert this behavior use the new setting:</p> +<pre><code>REST_FRAMEWORK = { + 'UNICODE_JSON': False +} +</code></pre> +<h4 id="compact-json-by-default">Compact JSON by default.</h4> +<p>We now output compact JSON in responses by default. For example, we return:</p> +<pre><code>{"email":"amy@example.com","is_admin":true} +</code></pre> +<p>Instead of the following:</p> +<pre><code>{"email": "amy@example.com", "is_admin": true} +</code></pre> +<p>The <code>COMPACT_JSON</code> setting has been added, and can be used to revert this behavior if needed:</p> +<pre><code>REST_FRAMEWORK = { + 'COMPACT_JSON': False +} +</code></pre> +<h4 id="file-fields-as-urls">File fields as URLs</h4> +<p>The <code>FileField</code> and <code>ImageField</code> classes are now represented as URLs by default. You should ensure you set Django's <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_URL">standard <code>MEDIA_URL</code> setting</a> appropriately, and ensure your application <a href="https://docs.djangoproject.com/en/dev/howto/static-files/#serving-uploaded-files-in-development">serves the uploaded files</a>.</p> +<p>You can revert this behavior, and display filenames in the representation by using the <code>UPLOADED_FILES_USE_URL</code> settings key:</p> +<pre><code>REST_FRAMEWORK = { + 'UPLOADED_FILES_USE_URL': False +} +</code></pre> +<p>You can also modify serializer fields individually, using the <code>use_url</code> argument:</p> +<pre><code>uploaded_file = serializers.FileField(use_url=False) +</code></pre> +<p>Also note that you should pass the <code>request</code> object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form <code>https://example.com/url_path/filename.txt</code>. For example:</p> +<pre><code>context = {'request': request} +serializer = ExampleSerializer(instance, context=context) +return Response(serializer.data) +</code></pre> +<p>If the request is omitted from the context, the returned URLs will be of the form <code>/url_path/filename.txt</code>.</p> +<h4 id="throttle-headers-using-retry-after">Throttle headers using <code>Retry-After</code>.</h4> +<p>The custom <code>X-Throttle-Wait-Second</code> header has now been dropped in favor of the standard <code>Retry-After</code> header. You can revert this behavior if needed by writing a custom exception handler for your application.</p> +<h4 id="date-and-time-objects-as-iso-8859-1-strings-in-serializer-data">Date and time objects as ISO-8859-1 strings in serializer data.</h4> +<p>Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as <code>Date</code>, <code>Time</code> and <code>DateTime</code> objects, and later coerced to strings by the renderer.</p> +<p>You can modify this behavior globally by settings the existing <code>DATE_FORMAT</code>, <code>DATETIME_FORMAT</code> and <code>TIME_FORMAT</code> settings keys. Setting these values to <code>None</code> instead of their default value of <code>'iso-8859-1'</code> will result in native objects being returned in serializer data.</p> +<pre><code>REST_FRAMEWORK = { + # Return native `Date` and `Time` objects in `serializer.data` + 'DATETIME_FORMAT': None + 'DATE_FORMAT': None + 'TIME_FORMAT': None +} +</code></pre> +<p>You can also modify serializer fields individually, using the <code>date_format</code>, <code>time_format</code> and <code>datetime_format</code> arguments:</p> +<pre><code># Return `DateTime` instances in `serializer.data`, not strings. +created = serializers.DateTimeField(format=None) +</code></pre> +<h4 id="decimals-as-strings-in-serializer-data">Decimals as strings in serializer data.</h4> +<p>Decimals are now coerced to strings by default in the serializer output. Previously they were returned as <code>Decimal</code> objects, and later coerced to strings by the renderer.</p> +<p>You can modify this behavior globally by using the <code>COERCE_DECIMAL_TO_STRING</code> settings key.</p> +<pre><code>REST_FRAMEWORK = { + 'COERCE_DECIMAL_TO_STRING': False +} +</code></pre> +<p>Or modify it on an individual serializer field, using the <code>coerce_to_string</code> keyword argument.</p> +<pre><code># Return `Decimal` instances in `serializer.data`, not strings. +amount = serializers.DecimalField( + max_digits=10, + decimal_places=2, + coerce_to_string=False +) +</code></pre> +<p>The default JSON renderer will return float objects for un-coerced <code>Decimal</code> instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.</p> +<hr /> +<h2 id="miscellaneous-notes">Miscellaneous notes</h2> +<ul> +<li>The serializer <code>ChoiceField</code> does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.</li> +<li>Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.</li> +</ul> +<hr /> +<h2 id="whats-coming-next">What's coming next</h2> +<p>3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.</p> +<p>The 3.1 release is planned to address improvements in the following components:</p> +<ul> +<li>Public API for using serializers as HTML forms.</li> +<li>Request parsing, mediatypes & the implementation of the browsable API.</li> +<li>Introduction of a new pagination API.</li> +<li>Better support for API versioning.</li> +</ul> +<p>The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.</p> +<p>You can follow development on the GitHub site, where we use <a href="https://github.com/tomchristie/django-rest-framework/milestones">milestones to indicate planning timescales</a>.</p> + + </div> + <!--/span--> + </div> + <!--/row--> + </div> + <!--/.fluid-container--> + </div> + <!--/.body content--> + <div id="push"></div> + </div> + <!--/.wrapper --> + + <footer class="span12"> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> + </p> + </footer> + + <!-- Le javascript + ================================================== --> + <!-- Placed at the end of the document so the pages load faster --> + <script src="../../js/jquery-1.8.1-min.js"></script> + <script src="../../js/prettify-1.0.js"></script> + <script src="../../js/bootstrap-2.1.1-min.js"></script> + + <script> + //$('.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>
\ No newline at end of file diff --git a/topics/ajax-csrf-cors/index.html b/topics/ajax-csrf-cors/index.html index 34f00dac..d49dfa82 100644 --- a/topics/ajax-csrf-cors/index.html +++ b/topics/ajax-csrf-cors/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -402,7 +410,7 @@ <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/browsable-api/index.html b/topics/browsable-api/index.html index 80dc38ae..d1cc6d30 100644 --- a/topics/browsable-api/index.html +++ b/topics/browsable-api/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -460,28 +468,18 @@ <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><code>{% block script %} -{{ block.super }} -{% include 'autocomplete_light/static.html' %} -{% endblock %} +<h4 id="handling-choicefield-with-large-numbers-of-items">Handling <code>ChoiceField</code> with large numbers of items.</h4> +<p>When a relationship or <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.</p> +<p>The simplest option in this case is to replace the select input with a standard text input. For example:</p> +<pre><code> author = serializers.HyperlinkedRelatedField( + queryset=User.objects.all(), + style={'base_template': 'input.html'} +) </code></pre> -<p>You can now add the <code>autocomplete_light.ChoiceWidget</code> widget to the serializer field.</p> -<pre><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> +<h4 id="autocomplete">Autocomplete</h4> +<p>An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.</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>, that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the <code>widget</code> keyword argument since it now uses templated HTML generation.</p> +<p>Better support for autocomplete inputs is planned in future versions.</p> <hr /> </div> @@ -497,7 +495,7 @@ class BookSerializer(serializers.ModelSerializer): <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/browser-enhancements/index.html b/topics/browser-enhancements/index.html index d05dad67..63178484 100644 --- a/topics/browser-enhancements/index.html +++ b/topics/browser-enhancements/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -445,7 +453,7 @@ as well as how to support content types other than form-encoded data.</p> <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/contributing/index.html b/topics/contributing/index.html index 690b9dc5..a8ec0e2b 100644 --- a/topics/contributing/index.html +++ b/topics/contributing/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -518,7 +526,6 @@ pip install -r requirements-test.txt <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 abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.</li> </ul> <h2 id="markdown-style">Markdown style</h2> @@ -566,7 +573,7 @@ More text... <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/credits/index.html b/topics/credits/index.html index 536e0957..1dc44a1b 100644 --- a/topics/credits/index.html +++ b/topics/credits/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -572,7 +580,7 @@ <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/documenting-your-api/index.html b/topics/documenting-your-api/index.html index 1d68e657..db43a2ea 100644 --- a/topics/documenting-your-api/index.html +++ b/topics/documenting-your-api/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -441,7 +449,7 @@ <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/kickstarter-announcement/index.html b/topics/kickstarter-announcement/index.html index e27aafc3..3ff599c5 100644 --- a/topics/kickstarter-announcement/index.html +++ b/topics/kickstarter-announcement/index.html @@ -65,7 +65,7 @@ <a class="repo-link btn btn-inverse btn-small " rel="prev" href="../release-notes"> Next <i class="icon-arrow-right icon-white"></i> </a> - <a class="repo-link btn btn-inverse btn-small " rel="next" href="../2.4-announcement"> + <a class="repo-link btn btn-inverse btn-small " rel="next" href="../3.0-announcement"> <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> @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -263,6 +267,10 @@ <a href="../2.4-announcement">2.4 Announcement</a> </li> + <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + <li class="active" > <a href=".">Kickstarter Announcement</a> </li> @@ -509,7 +517,7 @@ <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/release-notes/index.html b/topics/release-notes/index.html index 227e2640..6534fa05 100644 --- a/topics/release-notes/index.html +++ b/topics/release-notes/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -373,22 +381,6 @@ <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> - @@ -790,7 +782,7 @@ <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> +<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="../../ticket-582">ticket 582</a> for more details.</p> <h3 id="2115">2.1.15</h3> <p><strong>Date</strong>: 3rd Jan 2013</p> <ul> @@ -936,124 +928,7 @@ <li><strong>Fix all of the things.</strong> (Well, almost.)</li> <li>For more information please see the <a href="../rest-framework-2-announcement">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> +<p>For older release notes, <a href="../../old-release-notes">please see the GitHub repo</a>.</p> </div> <!--/span--> @@ -1068,7 +943,7 @@ <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/rest-framework-2-announcement/index.html b/topics/rest-framework-2-announcement/index.html index ebe6dfea..2a39eea1 100644 --- a/topics/rest-framework-2-announcement/index.html +++ b/topics/rest-framework-2-announcement/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -452,7 +460,7 @@ <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/rest-hypermedia-hateoas/index.html b/topics/rest-hypermedia-hateoas/index.html index 424d2514..ce8ea833 100644 --- a/topics/rest-hypermedia-hateoas/index.html +++ b/topics/rest-hypermedia-hateoas/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -368,11 +376,11 @@ <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>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>First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and 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 API, 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 @@ -390,7 +398,7 @@ the Design of Network-based Software Architectures</a>.</li> <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">serialization</a> and <a href="../../api-guide/parsers">parser</a>/<a href="../../api-guide/renderers">renderer</a> components that make it easy to build appropriate media types, <a href="../../api-guide/fields">hyperlinked relations</a> for building well-connected systems, and great support for <a href="../../api-guide/content-negotiation">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> +<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--> @@ -405,7 +413,7 @@ the Design of Network-based Software Architectures</a>.</li> <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> diff --git a/topics/third-party-resources/index.html b/topics/third-party-resources/index.html index 0e332908..529a7b5a 100644 --- a/topics/third-party-resources/index.html +++ b/topics/third-party-resources/index.html @@ -165,6 +165,10 @@ </li> <li > + <a href="../../api-guide/validators">Validators</a> + </li> + + <li > <a href="../../api-guide/authentication">Authentication</a> </li> @@ -264,6 +268,10 @@ </li> <li > + <a href="../3.0-announcement">3.0 Announcement</a> + </li> + + <li > <a href="../kickstarter-announcement">Kickstarter Announcement</a> </li> @@ -373,9 +381,9 @@ <h1 id="third-party-resources">Third Party Resources</h1> <h2 id="about-third-party-packages">About Third Party Packages</h2> <p>Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.</p> -<p>We <strong>support</strong>, <strong>encourage</strong> and <strong>strongly favour</strong> the creation of Third Party Packages to encapsulate new behaviour rather than adding additional functionality directly to Django REST Framework.</p> -<p>We aim to make creating Third Party Packages as easy as possible, whilst keeping the <strong>simplicity</strong> of the core API and ensuring that <strong>maintenance</strong> of the main project remains under control. If a Third Party Package proves popular it is relatively easy to move it into the main project; removing features is much more problematic.</p> -<p>If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to dicuss ideas on the <a href="https://groups.google.com/forum/#!forum/django-rest-framework">Mailing List</a>.</p> +<p>We <strong>support</strong>, <strong>encourage</strong> and <strong>strongly favor</strong> the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.</p> +<p>We aim to make creating third party packages as easy as possible, whilst keeping a <strong>simple</strong> and <strong>well maintained</strong> core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.</p> +<p>If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the <a href="https://groups.google.com/forum/#!forum/django-rest-framework">Mailing List</a>.</p> <h2 id="how-to-create-a-third-party-package">How to create a Third Party Package</h2> <h3 id="creating-your-package">Creating your package</h3> <p>You can use <a href="https://github.com/jpadilla/cookiecutter-django-rest-framework">this cookiecutter template</a> for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.</p> @@ -581,7 +589,7 @@ You probably want to also tag the version now: <!--/.wrapper --> <footer class="span12"> - <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a> + <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a> </p> </footer> |
