@@ -465,22 +490,25 @@
Serialization that supports both ORM and non-ORM data sources.
Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
Extensive documentation, and great community support.
-Used and trusted by large companies such as Mozilla and Eventbrite.
+Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
-We are a collaboratively funded project.
-Many thanks to our sponsors for ensuring we can continue to develop, support and improve Django REST framework.
-Rover.com
+
+REST framework is a collaboratively funded project. If you use
+REST framework commercially we strongly encourage you to invest in its
+continued development by signing up for a paid plan.
+The initial aim is to provide a single full-time position on REST framework.
+Right now we're a little over 43% of the way towards achieving that.
+Every single sign-up makes a significant impact. Taking out a
+basic tier sponsorship moves us about 1% closer to our funding target.
+
+
+
+
+Many thanks to all our awesome sponsors, and in particular to our premium backers, Rover and Sentry.
REST framework requires the following:
diff --git a/js/bootstrap-2.1.1-min.js b/js/bootstrap-2.1.1-min.js
old mode 100644
new mode 100755
diff --git a/mkdocs/js/search.js b/mkdocs/js/search.js
index f4ebcf3bb..0bdb5b04c 100644
--- a/mkdocs/js/search.js
+++ b/mkdocs/js/search.js
@@ -15,7 +15,7 @@ require([
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == 'q')
{
- return sParameterName[1];
+ return decodeURIComponent(sParameterName[1].replace(/\+/g, '%20'));
}
}
}
diff --git a/mkdocs/search_index.json b/mkdocs/search_index.json
index 1d75250b5..916d535df 100644
--- a/mkdocs/search_index.json
+++ b/mkdocs/search_index.json
@@ -2,9 +2,14 @@
"docs": [
{
"location": "/",
- "text": "Note\n: This is the documentation for the \nversion 3\n of REST framework. Documentation for \nversion 2\n is also available.\n\n\n\n\n\n\nDjango REST Framework\n\n\n\n\n\n\n\n\nDjango REST framework is a powerful and flexible toolkit for building Web APIs.\n\n\nSome reasons you might want to use REST framework:\n\n\n\n\nThe \nWeb browsable API\n is a huge usability win for your developers.\n\n\nAuthentication policies\n including packages for \nOAuth1a\n and \nOAuth2\n.\n\n\nSerialization\n that supports both \nORM\n and \nnon-ORM\n data sources.\n\n\nCustomizable all the way down - just use \nregular function-based views\n if you don't need the \nmore\n \npowerful\n \nfeatures\n.\n\n\nExtensive documentation\n, and \ngreat community support\n.\n\n\nUsed and trusted by large companies such as \nMozilla\n and \nEventbrite\n.\n\n\n\n\n\n\nWe are a \ncollaboratively funded project\n.\nMany thanks to our sponsors for ensuring we can continue to develop, support and improve Django REST framework.\n\n\nRover.com\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.2, 3.3, 3.4, 3.5)\n\n\nDjango (1.7+, 1.8, 1.9)\n\n\n\n\nThe following packages are optional:\n\n\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (0.9.2+) - Filtering support.\n\n\ndjango-crispy-forms\n - Improved HTML display for filtering.\n\n\ndjango-guardian\n (1.1.1+) - Object level permissions support.\n\n\n\n\nInstallation\n\n\nInstall using \npip\n, including any optional packages you want...\n\n\npip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n\n\n\n...or clone the project from github.\n\n\ngit clone git@github.com:tomchristie/django-rest-framework.git\n\n\n\nAdd \n'rest_framework'\n to your \nINSTALLED_APPS\n setting.\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nIf you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root \nurls.py\n file.\n\n\nurlpatterns = [\n ...\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nNote that the URL path can be whatever you want, but you must include \n'rest_framework.urls'\n with the \n'rest_framework'\n namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.\n\n\nExample\n\n\nLet's take a look at a quick example of using REST framework to build a simple model-backed API.\n\n\nWe'll create a read-write API for accessing information on the users of our project.\n\n\nAny global settings for a REST framework API are kept in a single configuration dictionary named \nREST_FRAMEWORK\n. Start off by adding the following to your \nsettings.py\n module:\n\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n\n\n\nDon't forget to make sure you've also added \nrest_framework\n to your \nINSTALLED_APPS\n.\n\n\nWe're ready to create our API now.\nHere's our project's root \nurls.py\n module:\n\n\nfrom django.conf.urls import url, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'is_staff')\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nYou can now open the API in your browser at \nhttp://127.0.0.1:8000/\n, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.\n\n\nQuickstart\n\n\nCan't wait to get started? The \nquickstart guide\n is the fastest way to get up and running, and building APIs with REST framework.\n\n\nTutorial\n\n\nThe tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.\n\n\n\n\n1 - Serialization\n\n\n2 - Requests \n Responses\n\n\n3 - Class based views\n\n\n4 - Authentication \n permissions\n\n\n5 - Relationships \n hyperlinked APIs\n\n\n6 - Viewsets \n routers\n\n\n\n\nThere is a live example API of the finished tutorial API for testing purposes, \navailable here\n.\n\n\nAPI Guide\n\n\nThe API guide is your complete reference manual to all the functionality provided by REST framework.\n\n\n\n\nRequests\n\n\nResponses\n\n\nViews\n\n\nGeneric views\n\n\nViewsets\n\n\nRouters\n\n\nParsers\n\n\nRenderers\n\n\nSerializers\n\n\nSerializer fields\n\n\nSerializer relations\n\n\nValidators\n\n\nAuthentication\n\n\nPermissions\n\n\nThrottling\n\n\nFiltering\n\n\nPagination\n\n\nVersioning\n\n\nContent negotiation\n\n\nMetadata\n\n\nFormat suffixes\n\n\nReturning URLs\n\n\nExceptions\n\n\nStatus codes\n\n\nTesting\n\n\nSettings\n\n\n\n\nTopics\n\n\nGeneral guides to using REST framework.\n\n\n\n\nDocumenting your API\n\n\nInternationalization\n\n\nAJAX, CSRF \n CORS\n\n\nHTML \n Forms\n\n\nBrowser enhancements\n\n\nThe Browsable API\n\n\nREST, Hypermedia \n HATEOAS\n\n\nThird Party Resources\n\n\nContributing to REST framework\n\n\nProject management\n\n\n3.0 Announcement\n\n\n3.1 Announcement\n\n\n3.2 Announcement\n\n\n3.3 Announcement\n\n\nKickstarter Announcement\n\n\nMozilla Grant\n\n\nFunding\n\n\nRelease Notes\n\n\n\n\nDevelopment\n\n\nSee the \nContribution guidelines\n for information on how to clone\nthe repository, run the test suite and contribute changes back to REST\nFramework.\n\n\nSupport\n\n\nFor support please see the \nREST framework discussion group\n, try the \n#restframework\n channel on \nirc.freenode.net\n, search \nthe IRC archives\n, or raise a question on \nStack Overflow\n, making sure to include the \n'django-rest-framework'\n tag.\n\n\nPaid support is available\n from \nDabApps\n, and can include work on REST framework core, or support with building your REST framework API. Please \ncontact DabApps\n if you'd like to discuss commercial support options.\n\n\nFor updates on REST framework development, you may also want to follow \nthe author\n on Twitter.\n\n\nFollow @_tomchristie\n\n\n!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");\n\n\nSecurity\n\n\nIf you believe you\u2019ve found something in Django REST framework which has security implications, please \ndo not raise the issue in a public forum\n.\n\n\nSend a description of the issue via email to \nrest-framework-security@googlegroups.com\n. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.\n\n\nLicense\n\n\nCopyright (c) 2011-2016, Tom Christie\nAll rights reserved.\n\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
+ "text": ".promo li a {\n float: left;\n width: 130px;\n height: 20px;\n text-align: center;\n margin: 10px 30px;\n padding: 150px 0 0 0;\n background-position: 0 50%;\n background-size: 130px auto;\n background-repeat: no-repeat;\n font-size: 120%;\n color: black;\n}\n.promo li {\n list-style: none;\n}\n\n\n\n\n\n \n\n\n \n\n \n\n \n\n\n \n\n \n\n \n\n\n\n\n\n\n\nNote\n: This is the documentation for the \nversion 3\n of REST framework. Documentation for \nversion 2\n is also available.\n\n\n\n\n\n\nDjango REST Framework\n\n\n\n\n\n\n\n\nDjango REST framework is a powerful and flexible toolkit for building Web APIs.\n\n\nSome reasons you might want to use REST framework:\n\n\n\n\nThe \nWeb browsable API\n is a huge usability win for your developers.\n\n\nAuthentication policies\n including packages for \nOAuth1a\n and \nOAuth2\n.\n\n\nSerialization\n that supports both \nORM\n and \nnon-ORM\n data sources.\n\n\nCustomizable all the way down - just use \nregular function-based views\n if you don't need the \nmore\n \npowerful\n \nfeatures\n.\n\n\nExtensive documentation\n, and \ngreat community support\n.\n\n\nUsed and trusted by internationally recognised companies including \nMozilla\n, \nRed Hat\n, \nHeroku\n, and \nEventbrite\n.\n\n\n\n\n\n\nFunding\n\n\nREST framework is a \ncollaboratively funded project\n. If you use\nREST framework commercially we strongly encourage you to invest in its\ncontinued development by \nsigning up for a paid plan\n.\n\n\nThe initial aim is to provide a single full-time position on REST framework.\nRight now we're a little over 43% of the way towards achieving that.\n\nEvery single sign-up makes a significant impact.\n Taking out a\n\nbasic tier sponsorship\n moves us about 1% closer to our funding target.\n\n\n\n \nRover.com\n\n \nSentry\n\n\n\n\n\n\n\n\nMany thanks to all our \nawesome sponsors\n, and in particular to our premium backers, \nRover\n and \nSentry\n.\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.2, 3.3, 3.4, 3.5)\n\n\nDjango (1.7+, 1.8, 1.9)\n\n\n\n\nThe following packages are optional:\n\n\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (0.9.2+) - Filtering support.\n\n\ndjango-crispy-forms\n - Improved HTML display for filtering.\n\n\ndjango-guardian\n (1.1.1+) - Object level permissions support.\n\n\n\n\nInstallation\n\n\nInstall using \npip\n, including any optional packages you want...\n\n\npip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n\n\n\n...or clone the project from github.\n\n\ngit clone git@github.com:tomchristie/django-rest-framework.git\n\n\n\nAdd \n'rest_framework'\n to your \nINSTALLED_APPS\n setting.\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nIf you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root \nurls.py\n file.\n\n\nurlpatterns = [\n ...\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nNote that the URL path can be whatever you want, but you must include \n'rest_framework.urls'\n with the \n'rest_framework'\n namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.\n\n\nExample\n\n\nLet's take a look at a quick example of using REST framework to build a simple model-backed API.\n\n\nWe'll create a read-write API for accessing information on the users of our project.\n\n\nAny global settings for a REST framework API are kept in a single configuration dictionary named \nREST_FRAMEWORK\n. Start off by adding the following to your \nsettings.py\n module:\n\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n\n\n\nDon't forget to make sure you've also added \nrest_framework\n to your \nINSTALLED_APPS\n.\n\n\nWe're ready to create our API now.\nHere's our project's root \nurls.py\n module:\n\n\nfrom django.conf.urls import url, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'is_staff')\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nYou can now open the API in your browser at \nhttp://127.0.0.1:8000/\n, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.\n\n\nQuickstart\n\n\nCan't wait to get started? The \nquickstart guide\n is the fastest way to get up and running, and building APIs with REST framework.\n\n\nTutorial\n\n\nThe tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.\n\n\n\n\n1 - Serialization\n\n\n2 - Requests \n Responses\n\n\n3 - Class based views\n\n\n4 - Authentication \n permissions\n\n\n5 - Relationships \n hyperlinked APIs\n\n\n6 - Viewsets \n routers\n\n\n\n\nThere is a live example API of the finished tutorial API for testing purposes, \navailable here\n.\n\n\nAPI Guide\n\n\nThe API guide is your complete reference manual to all the functionality provided by REST framework.\n\n\n\n\nRequests\n\n\nResponses\n\n\nViews\n\n\nGeneric views\n\n\nViewsets\n\n\nRouters\n\n\nParsers\n\n\nRenderers\n\n\nSerializers\n\n\nSerializer fields\n\n\nSerializer relations\n\n\nValidators\n\n\nAuthentication\n\n\nPermissions\n\n\nThrottling\n\n\nFiltering\n\n\nPagination\n\n\nVersioning\n\n\nContent negotiation\n\n\nMetadata\n\n\nFormat suffixes\n\n\nReturning URLs\n\n\nExceptions\n\n\nStatus codes\n\n\nTesting\n\n\nSettings\n\n\n\n\nTopics\n\n\nGeneral guides to using REST framework.\n\n\n\n\nDocumenting your API\n\n\nInternationalization\n\n\nAJAX, CSRF \n CORS\n\n\nHTML \n Forms\n\n\nBrowser enhancements\n\n\nThe Browsable API\n\n\nREST, Hypermedia \n HATEOAS\n\n\nThird Party Resources\n\n\nContributing to REST framework\n\n\nProject management\n\n\n3.0 Announcement\n\n\n3.1 Announcement\n\n\n3.2 Announcement\n\n\n3.3 Announcement\n\n\nKickstarter Announcement\n\n\nMozilla Grant\n\n\nFunding\n\n\nRelease Notes\n\n\n\n\nDevelopment\n\n\nSee the \nContribution guidelines\n for information on how to clone\nthe repository, run the test suite and contribute changes back to REST\nFramework.\n\n\nSupport\n\n\nFor support please see the \nREST framework discussion group\n, try the \n#restframework\n channel on \nirc.freenode.net\n, search \nthe IRC archives\n, or raise a question on \nStack Overflow\n, making sure to include the \n'django-rest-framework'\n tag.\n\n\nPaid support is available\n from \nDabApps\n, and can include work on REST framework core, or support with building your REST framework API. Please \ncontact DabApps\n if you'd like to discuss commercial support options.\n\n\nFor updates on REST framework development, you may also want to follow \nthe author\n on Twitter.\n\n\nFollow @_tomchristie\n\n\n!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");\n\n\nSecurity\n\n\nIf you believe you\u2019ve found something in Django REST framework which has security implications, please \ndo not raise the issue in a public forum\n.\n\n\nSend a description of the issue via email to \nrest-framework-security@googlegroups.com\n. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.\n\n\nLicense\n\n\nCopyright (c) 2011-2016, Tom Christie\nAll rights reserved.\n\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"title": "Home"
},
+ {
+ "location": "/#funding",
+ "text": "REST framework is a collaboratively funded project . If you use\nREST framework commercially we strongly encourage you to invest in its\ncontinued development by signing up for a paid plan . The initial aim is to provide a single full-time position on REST framework.\nRight now we're a little over 43% of the way towards achieving that. Every single sign-up makes a significant impact. Taking out a basic tier sponsorship moves us about 1% closer to our funding target. \n Rover.com \n Sentry Many thanks to all our awesome sponsors , and in particular to our premium backers, Rover and Sentry .",
+ "title": "Funding"
+ },
{
"location": "/#requirements",
"text": "REST framework requires the following: Python (2.7, 3.2, 3.3, 3.4, 3.5) Django (1.7+, 1.8, 1.9) The following packages are optional: Markdown (2.1.0+) - Markdown support for the browsable API. django-filter (0.9.2+) - Filtering support. django-crispy-forms - Improved HTML display for filtering. django-guardian (1.1.1+) - Object level permissions support.",
@@ -62,7 +67,7 @@
},
{
"location": "/tutorial/quickstart/",
- "text": "Quickstart\n\n\nWe're going to create a simple API to allow admin users to view and edit the users and groups in the system.\n\n\nProject setup\n\n\nCreate a new Django project named \ntutorial\n, then start a new app called \nquickstart\n.\n\n\n# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtualenv to isolate our package dependencies locally\nvirtualenv env\nsource env/bin/activate # On Windows use `env\\Scripts\\activate`\n\n# Install Django and Django REST framework into the virtualenv\npip install django\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin.py startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin.py startapp quickstart\ncd ..\n\n\n\nNow sync your database for the first time:\n\n\npython manage.py migrate\n\n\n\nWe'll also create an initial user named \nadmin\n with a password of \npassword123\n. We'll authenticate as that user later in our example.\n\n\npython manage.py createsuperuser\n\n\n\nOnce you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...\n\n\nSerializers\n\n\nFirst up we're going to define some serializers. Let's create a new module named \ntutorial/quickstart/serializers.py\n that we'll use for our data representations.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import serializers\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'groups')\n\n\nclass GroupSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Group\n fields = ('url', 'name')\n\n\n\nNotice that we're using hyperlinked relations in this case, with \nHyperlinkedModelSerializer\n. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.\n\n\nViews\n\n\nRight, we'd better write some views then. Open \ntutorial/quickstart/views.py\n and get typing.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import viewsets\nfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = User.objects.all().order_by('-date_joined')\n serializer_class = UserSerializer\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n\n\n\nRather than write multiple views we're grouping together all the common behavior into classes called \nViewSets\n.\n\n\nWe can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.\n\n\nURLs\n\n\nOkay, now let's wire up the API URLs. On to \ntutorial/urls.py\n...\n\n\nfrom django.conf.urls import url, include\nfrom rest_framework import routers\nfrom tutorial.quickstart import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'groups', views.GroupViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nBecause we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.\n\n\nAgain, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.\n\n\nFinally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.\n\n\nSettings\n\n\nWe'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in \ntutorial/settings.py\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),\n 'PAGE_SIZE': 10\n}\n\n\n\nOkay, we're done.\n\n\n\n\nTesting our API\n\n\nWe're now ready to test the API we've built. Let's fire up the server from the command line.\n\n\npython ./manage.py runserver\n\n\n\nWe can now access our API, both from the command-line, using tools like \ncurl\n...\n\n\nbash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr using the \nhttpie\n, command line tool...\n\n\nbash: http -a admin:password123 http://127.0.0.1:8000/users/\n\nHTTP/1.1 200 OK\n...\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://localhost:8000/users/1/\",\n \"username\": \"paul\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr directly through the browser...\n\n\n\n\nIf you're working through the browser, make sure to login using the control in the top right corner.\n\n\nGreat, that was easy!\n\n\nIf you want to get a more in depth understanding of how REST framework fits together head on over to \nthe tutorial\n, or start browsing the \nAPI guide\n.",
+ "text": "Quickstart\n\n\nWe're going to create a simple API to allow admin users to view and edit the users and groups in the system.\n\n\nProject setup\n\n\nCreate a new Django project named \ntutorial\n, then start a new app called \nquickstart\n.\n\n\n# Create the project directory\nmkdir tutorial\ncd tutorial\n\n# Create a virtualenv to isolate our package dependencies locally\nvirtualenv env\nsource env/bin/activate # On Windows use `env\\Scripts\\activate`\n\n# Install Django and Django REST framework into the virtualenv\npip install django\npip install djangorestframework\n\n# Set up a new project with a single application\ndjango-admin.py startproject tutorial . # Note the trailing '.' character\ncd tutorial\ndjango-admin.py startapp quickstart\ncd ..\n\n\n\nNow sync your database for the first time:\n\n\npython manage.py migrate\n\n\n\nWe'll also create an initial user named \nadmin\n with a password of \npassword123\n. We'll authenticate as that user later in our example.\n\n\npython manage.py createsuperuser\n\n\n\nOnce you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...\n\n\nSerializers\n\n\nFirst up we're going to define some serializers. Let's create a new module named \ntutorial/quickstart/serializers.py\n that we'll use for our data representations.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import serializers\n\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'groups')\n\n\nclass GroupSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Group\n fields = ('url', 'name')\n\n\n\nNotice that we're using hyperlinked relations in this case, with \nHyperlinkedModelSerializer\n. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.\n\n\nViews\n\n\nRight, we'd better write some views then. Open \ntutorial/quickstart/views.py\n and get typing.\n\n\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import viewsets\nfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = User.objects.all().order_by('-date_joined')\n serializer_class = UserSerializer\n\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n\n\n\nRather than write multiple views we're grouping together all the common behavior into classes called \nViewSets\n.\n\n\nWe can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.\n\n\nURLs\n\n\nOkay, now let's wire up the API URLs. On to \ntutorial/urls.py\n...\n\n\nfrom django.conf.urls import url, include\nfrom rest_framework import routers\nfrom tutorial.quickstart import views\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'groups', views.GroupViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nBecause we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.\n\n\nAgain, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.\n\n\nFinally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.\n\n\nSettings\n\n\nWe'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in \ntutorial/settings.py\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),\n 'PAGE_SIZE': 10\n}\n\n\n\nOkay, we're done.\n\n\n\n\nTesting our API\n\n\nWe're now ready to test the API we've built. Let's fire up the server from the command line.\n\n\npython manage.py runserver\n\n\n\nWe can now access our API, both from the command-line, using tools like \ncurl\n...\n\n\nbash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr using the \nhttpie\n, command line tool...\n\n\nbash: http -a admin:password123 http://127.0.0.1:8000/users/\n\nHTTP/1.1 200 OK\n...\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://localhost:8000/users/1/\",\n \"username\": \"paul\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n}\n\n\n\nOr directly through the browser, by going to the URL \nhttp://127.0.0.1:8000/users/\n...\n\n\n\n\nIf you're working through the browser, make sure to login using the control in the top right corner.\n\n\nGreat, that was easy!\n\n\nIf you want to get a more in depth understanding of how REST framework fits together head on over to \nthe tutorial\n, or start browsing the \nAPI guide\n.",
"title": "Quickstart"
},
{
@@ -97,7 +102,7 @@
},
{
"location": "/tutorial/quickstart/#testing-our-api",
- "text": "We're now ready to test the API we've built. Let's fire up the server from the command line. python ./manage.py runserver We can now access our API, both from the command-line, using tools like curl ... bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n} Or using the httpie , command line tool... bash: http -a admin:password123 http://127.0.0.1:8000/users/\n\nHTTP/1.1 200 OK\n...\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://localhost:8000/users/1/\",\n \"username\": \"paul\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n} Or directly through the browser... If you're working through the browser, make sure to login using the control in the top right corner. Great, that was easy! If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial , or start browsing the API guide .",
+ "text": "We're now ready to test the API we've built. Let's fire up the server from the command line. python manage.py runserver We can now access our API, both from the command-line, using tools like curl ... bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://127.0.0.1:8000/users/1/\",\n \"username\": \"admin\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n} Or using the httpie , command line tool... bash: http -a admin:password123 http://127.0.0.1:8000/users/\n\nHTTP/1.1 200 OK\n...\n{\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"email\": \"admin@example.com\",\n \"groups\": [],\n \"url\": \"http://localhost:8000/users/1/\",\n \"username\": \"paul\"\n },\n {\n \"email\": \"tom@example.com\",\n \"groups\": [ ],\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"username\": \"tom\"\n }\n ]\n} Or directly through the browser, by going to the URL http://127.0.0.1:8000/users/ ... If you're working through the browser, make sure to login using the control in the top right corner. Great, that was easy! If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial , or start browsing the API guide .",
"title": "Testing our API"
},
{
@@ -162,7 +167,7 @@
},
{
"location": "/tutorial/2-requests-and-responses/",
- "text": "Tutorial 2: Requests and Responses\n\n\nFrom this point we're going to really start covering the core of REST framework.\nLet's introduce a couple of essential building blocks.\n\n\nRequest objects\n\n\nREST framework introduces a \nRequest\n object that extends the regular \nHttpRequest\n, and provides more flexible request parsing. The core functionality of the \nRequest\n object is the \nrequest.data\n attribute, which is similar to \nrequest.POST\n, but more useful for working with Web APIs.\n\n\nrequest.POST # Only handles form data. Only works for 'POST' method.\nrequest.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.\n\n\n\nResponse objects\n\n\nREST framework also introduces a \nResponse\n object, which is a type of \nTemplateResponse\n that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.\n\n\nreturn Response(data) # Renders to content type as requested by the client.\n\n\n\nStatus codes\n\n\nUsing numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as \nHTTP_400_BAD_REQUEST\n in the \nstatus\n module. It's a good idea to use these throughout rather than using numeric identifiers.\n\n\nWrapping API views\n\n\nREST framework provides two wrappers you can use to write API views.\n\n\n\n\nThe \n@api_view\n decorator for working with function based views.\n\n\nThe \nAPIView\n class for working with class based views.\n\n\n\n\nThese wrappers provide a few bits of functionality such as making sure you receive \nRequest\n instances in your view, and adding context to \nResponse\n objects so that content negotiation can be performed.\n\n\nThe wrappers also provide behaviour such as returning \n405 Method Not Allowed\n responses when appropriate, and handling any \nParseError\n exception that occurs when accessing \nrequest.data\n with malformed input.\n\n\nPulling it all together\n\n\nOkay, let's go ahead and start using these new components to write a few views.\n\n\nWe don't need our \nJSONResponse\n class in \nviews.py\n anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.\n\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view(['GET', 'POST'])\ndef snippet_list(request):\n \"\"\"\n List all snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = SnippetSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\nOur instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.\n\n\nHere is the view for an individual snippet, in the \nviews.py\n module.\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a snippet instance.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = SnippetSerializer(snippet, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\nThis should all feel very familiar - it is not a lot different from working with regular Django views.\n\n\nNotice that we're no longer explicitly tying our requests or responses to a given content type. \nrequest.data\n can handle incoming \njson\n requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.\n\n\nAdding optional format suffixes to our URLs\n\n\nTo take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as \nhttp://example.com/api/items/4/.json\n.\n\n\nStart by adding a \nformat\n keyword argument to both of the views, like so.\n\n\ndef snippet_list(request, format=None):\n\n\n\nand\n\n\ndef snippet_detail(request, pk, format=None):\n\n\n\nNow update the \nurls.py\n file slightly, to append a set of \nformat_suffix_patterns\n in addition to the existing URLs.\n\n\nfrom django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n url(r'^snippets/$', views.snippet_list),\n url(r'^snippets/(?P\npk\n[0-9]+)$', views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n\n\nWe don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.\n\n\nHow's it looking?\n\n\nGo ahead and test the API from the command line, as we did in \ntutorial part 1\n. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.\n\n\nWe can get a list of all of the snippets, as before.\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n\n\n\nWe can control the format of the response that we get back, either by using the \nAccept\n header:\n\n\nhttp http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML\n\n\n\nOr by appending a format suffix:\n\n\nhttp http://127.0.0.1:8000/snippets.json # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api # Browsable API suffix\n\n\n\nSimilarly, we can control the format of the request that we send, using the \nContent-Type\n header.\n\n\n# POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print 123\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print 456\"\n\n{\n \"id\": 4,\n \"title\": \"\",\n \"code\": \"print 456\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n\n\nNow go and open the API in a web browser, by visiting \nhttp://127.0.0.1:8000/snippets/\n.\n\n\nBrowsability\n\n\nBecause the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.\n\n\nHaving a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.\n\n\nSee the \nbrowsable api\n topic for more information about the browsable API feature and how to customize it.\n\n\nWhat's next?\n\n\nIn \ntutorial part 3\n, we'll start using class based views, and see how generic views reduce the amount of code we need to write.",
+ "text": "Tutorial 2: Requests and Responses\n\n\nFrom this point we're going to really start covering the core of REST framework.\nLet's introduce a couple of essential building blocks.\n\n\nRequest objects\n\n\nREST framework introduces a \nRequest\n object that extends the regular \nHttpRequest\n, and provides more flexible request parsing. The core functionality of the \nRequest\n object is the \nrequest.data\n attribute, which is similar to \nrequest.POST\n, but more useful for working with Web APIs.\n\n\nrequest.POST # Only handles form data. Only works for 'POST' method.\nrequest.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.\n\n\n\nResponse objects\n\n\nREST framework also introduces a \nResponse\n object, which is a type of \nTemplateResponse\n that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.\n\n\nreturn Response(data) # Renders to content type as requested by the client.\n\n\n\nStatus codes\n\n\nUsing numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as \nHTTP_400_BAD_REQUEST\n in the \nstatus\n module. It's a good idea to use these throughout rather than using numeric identifiers.\n\n\nWrapping API views\n\n\nREST framework provides two wrappers you can use to write API views.\n\n\n\n\nThe \n@api_view\n decorator for working with function based views.\n\n\nThe \nAPIView\n class for working with class based views.\n\n\n\n\nThese wrappers provide a few bits of functionality such as making sure you receive \nRequest\n instances in your view, and adding context to \nResponse\n objects so that content negotiation can be performed.\n\n\nThe wrappers also provide behaviour such as returning \n405 Method Not Allowed\n responses when appropriate, and handling any \nParseError\n exception that occurs when accessing \nrequest.data\n with malformed input.\n\n\nPulling it all together\n\n\nOkay, let's go ahead and start using these new components to write a few views.\n\n\nWe don't need our \nJSONResponse\n class in \nviews.py\n anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.\n\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n@api_view(['GET', 'POST'])\ndef snippet_list(request):\n \"\"\"\n List all snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = SnippetSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\nOur instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.\n\n\nHere is the view for an individual snippet, in the \nviews.py\n module.\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a snippet instance.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = SnippetSerializer(snippet, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\nThis should all feel very familiar - it is not a lot different from working with regular Django views.\n\n\nNotice that we're no longer explicitly tying our requests or responses to a given content type. \nrequest.data\n can handle incoming \njson\n requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.\n\n\nAdding optional format suffixes to our URLs\n\n\nTo take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as \nhttp://example.com/api/items/4/.json\n.\n\n\nStart by adding a \nformat\n keyword argument to both of the views, like so.\n\n\ndef snippet_list(request, format=None):\n\n\n\nand\n\n\ndef snippet_detail(request, pk, format=None):\n\n\n\nNow update the \nurls.py\n file slightly, to append a set of \nformat_suffix_patterns\n in addition to the existing URLs.\n\n\nfrom django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom snippets import views\n\nurlpatterns = [\n url(r'^snippets/$', views.snippet_list),\n url(r'^snippets/(?P\npk\n[0-9]+)$', views.snippet_detail),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n\n\nWe don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.\n\n\nHow's it looking?\n\n\nGo ahead and test the API from the command line, as we did in \ntutorial part 1\n. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.\n\n\nWe can get a list of all of the snippets, as before.\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n\n\n\nWe can control the format of the response that we get back, either by using the \nAccept\n header:\n\n\nhttp http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML\n\n\n\nOr by appending a format suffix:\n\n\nhttp http://127.0.0.1:8000/snippets.json # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api # Browsable API suffix\n\n\n\nSimilarly, we can control the format of the request that we send, using the \nContent-Type\n header.\n\n\n# POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print 123\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print 456\"\n\n{\n \"id\": 4,\n \"title\": \"\",\n \"code\": \"print 456\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n\n\nIf you add a \n--debug\n switch to the \nhttp\n requests above, you will be able to see the request type in request headers.\n\n\nNow go and open the API in a web browser, by visiting \nhttp://127.0.0.1:8000/snippets/\n.\n\n\nBrowsability\n\n\nBecause the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.\n\n\nHaving a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.\n\n\nSee the \nbrowsable api\n topic for more information about the browsable API feature and how to customize it.\n\n\nWhat's next?\n\n\nIn \ntutorial part 3\n, we'll start using class based views, and see how generic views reduce the amount of code we need to write.",
"title": "2 - Requests and responses"
},
{
@@ -202,9 +207,14 @@
},
{
"location": "/tutorial/2-requests-and-responses/#hows-it-looking",
- "text": "Go ahead and test the API from the command line, as we did in tutorial part 1 . Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests. We can get a list of all of the snippets, as before. http http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n] We can control the format of the response that we get back, either by using the Accept header: http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML Or by appending a format suffix: http http://127.0.0.1:8000/snippets.json # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api # Browsable API suffix Similarly, we can control the format of the request that we send, using the Content-Type header. # POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print 123\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print 456\"\n\n{\n \"id\": 4,\n \"title\": \"\",\n \"code\": \"print 456\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n} Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/ . Browsability Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation. Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API. See the browsable api topic for more information about the browsable API feature and how to customize it.",
+ "text": "Go ahead and test the API from the command line, as we did in tutorial part 1 . Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests. We can get a list of all of the snippets, as before. http http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n] We can control the format of the response that we get back, either by using the Accept header: http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON\nhttp http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML Or by appending a format suffix: http http://127.0.0.1:8000/snippets.json # JSON suffix\nhttp http://127.0.0.1:8000/snippets.api # Browsable API suffix Similarly, we can control the format of the request that we send, using the Content-Type header. # POST using form data\nhttp --form POST http://127.0.0.1:8000/snippets/ code=\"print 123\"\n\n{\n \"id\": 3,\n \"title\": \"\",\n \"code\": \"print 123\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n# POST using JSON\nhttp --json POST http://127.0.0.1:8000/snippets/ code=\"print 456\"\n\n{\n \"id\": 4,\n \"title\": \"\",\n \"code\": \"print 456\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n} If you add a --debug switch to the http requests above, you will be able to see the request type in request headers. Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/ .",
"title": "How's it looking?"
},
+ {
+ "location": "/tutorial/2-requests-and-responses/#browsability",
+ "text": "Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation. Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API. See the browsable api topic for more information about the browsable API feature and how to customize it.",
+ "title": "Browsability"
+ },
{
"location": "/tutorial/2-requests-and-responses/#whats-next",
"text": "In tutorial part 3 , we'll start using class based views, and see how generic views reduce the amount of code we need to write.",
@@ -243,7 +253,7 @@
{
"location": "/tutorial/4-authentication-and-permissions/#tutorial-4-authentication-permissions",
"text": "Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that: Code snippets are always associated with a creator. Only authenticated users may create snippets. Only the creator of a snippet may update or delete it. Unauthenticated requests should have full read-only access.",
- "title": "Tutorial 4: Authentication Permissions"
+ "title": "Tutorial 4: Authentication & Permissions"
},
{
"location": "/tutorial/4-authentication-and-permissions/#adding-information-to-our-model",
@@ -298,7 +308,7 @@
{
"location": "/tutorial/5-relationships-and-hyperlinked-apis/#tutorial-5-relationships-hyperlinked-apis",
"text": "At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.",
- "title": "Tutorial 5: Relationships Hyperlinked APIs"
+ "title": "Tutorial 5: Relationships & Hyperlinked APIs"
},
{
"location": "/tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-root-of-our-api",
@@ -338,7 +348,7 @@
{
"location": "/tutorial/6-viewsets-and-routers/#tutorial-6-viewsets-routers",
"text": "REST framework includes an abstraction for dealing with ViewSets , that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions. ViewSet classes are almost the same thing as View classes, except that they provide operations such as read , or update , and not method handlers such as get or put . A ViewSet class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a Router class which handles the complexities of defining the URL conf for you.",
- "title": "Tutorial 6: ViewSets Routers"
+ "title": "Tutorial 6: ViewSets & Routers"
},
{
"location": "/tutorial/6-viewsets-and-routers/#refactoring-to-use-viewsets",
@@ -542,24 +552,119 @@
},
{
"location": "/api-guide/views/#api-policy-attributes",
- "text": "The following attributes control the pluggable aspects of API views. .renderer_classes .parser_classes .authentication_classes .throttle_classes .permission_classes .content_negotiation_class",
+ "text": "The following attributes control the pluggable aspects of API views.",
"title": "API policy attributes"
},
+ {
+ "location": "/api-guide/views/#renderer_classes",
+ "text": "",
+ "title": ".renderer_classes"
+ },
+ {
+ "location": "/api-guide/views/#parser_classes",
+ "text": "",
+ "title": ".parser_classes"
+ },
+ {
+ "location": "/api-guide/views/#authentication_classes",
+ "text": "",
+ "title": ".authentication_classes"
+ },
+ {
+ "location": "/api-guide/views/#throttle_classes",
+ "text": "",
+ "title": ".throttle_classes"
+ },
+ {
+ "location": "/api-guide/views/#permission_classes",
+ "text": "",
+ "title": ".permission_classes"
+ },
+ {
+ "location": "/api-guide/views/#content_negotiation_class",
+ "text": "",
+ "title": ".content_negotiation_class"
+ },
{
"location": "/api-guide/views/#api-policy-instantiation-methods",
- "text": "The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods. .get_renderers(self) .get_parsers(self) .get_authenticators(self) .get_throttles(self) .get_permissions(self) .get_content_negotiator(self)",
+ "text": "The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.",
"title": "API policy instantiation methods"
},
+ {
+ "location": "/api-guide/views/#get_renderersself",
+ "text": "",
+ "title": ".get_renderers(self)"
+ },
+ {
+ "location": "/api-guide/views/#get_parsersself",
+ "text": "",
+ "title": ".get_parsers(self)"
+ },
+ {
+ "location": "/api-guide/views/#get_authenticatorsself",
+ "text": "",
+ "title": ".get_authenticators(self)"
+ },
+ {
+ "location": "/api-guide/views/#get_throttlesself",
+ "text": "",
+ "title": ".get_throttles(self)"
+ },
+ {
+ "location": "/api-guide/views/#get_permissionsself",
+ "text": "",
+ "title": ".get_permissions(self)"
+ },
+ {
+ "location": "/api-guide/views/#get_content_negotiatorself",
+ "text": "",
+ "title": ".get_content_negotiator(self)"
+ },
{
"location": "/api-guide/views/#api-policy-implementation-methods",
- "text": "The following methods are called before dispatching to the handler method. .check_permissions(self, request) .check_throttles(self, request) .perform_content_negotiation(self, request, force=False)",
+ "text": "The following methods are called before dispatching to the handler method.",
"title": "API policy implementation methods"
},
+ {
+ "location": "/api-guide/views/#check_permissionsself-request",
+ "text": "",
+ "title": ".check_permissions(self, request)"
+ },
+ {
+ "location": "/api-guide/views/#check_throttlesself-request",
+ "text": "",
+ "title": ".check_throttles(self, request)"
+ },
+ {
+ "location": "/api-guide/views/#perform_content_negotiationself-request-forcefalse",
+ "text": "",
+ "title": ".perform_content_negotiation(self, request, force=False)"
+ },
{
"location": "/api-guide/views/#dispatch-methods",
- "text": "The following methods are called directly by the view's .dispatch() method.\nThese perform any actions that need to occur before or after calling the handler methods such as .get() , .post() , put() , patch() and .delete() . .initial(self, request, *args, **kwargs) Performs any actions that need to occur before the handler method gets called.\nThis method is used to enforce permissions and throttling, and perform content negotiation. You won't typically need to override this method. .handle_exception(self, exc) Any exception thrown by the handler method will be passed to this method, which either returns a Response instance, or re-raises the exception. The default implementation handles any subclass of rest_framework.exceptions.APIException , as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response. If you need to customize the error responses your API returns you should subclass this method. .initialize_request(self, request, *args, **kwargs) Ensures that the request object that is passed to the handler method is an instance of Request , rather than the usual Django HttpRequest . You won't typically need to override this method. .finalize_response(self, request, response, *args, **kwargs) Ensures that any Response object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation. You won't typically need to override this method.",
+ "text": "The following methods are called directly by the view's .dispatch() method.\nThese perform any actions that need to occur before or after calling the handler methods such as .get() , .post() , put() , patch() and .delete() .",
"title": "Dispatch methods"
},
+ {
+ "location": "/api-guide/views/#initialself-request-42args-kwargs",
+ "text": "Performs any actions that need to occur before the handler method gets called.\nThis method is used to enforce permissions and throttling, and perform content negotiation. You won't typically need to override this method.",
+ "title": ".initial(self, request, *args, **kwargs)"
+ },
+ {
+ "location": "/api-guide/views/#handle_exceptionself-exc",
+ "text": "Any exception thrown by the handler method will be passed to this method, which either returns a Response instance, or re-raises the exception. The default implementation handles any subclass of rest_framework.exceptions.APIException , as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response. If you need to customize the error responses your API returns you should subclass this method.",
+ "title": ".handle_exception(self, exc)"
+ },
+ {
+ "location": "/api-guide/views/#initialize_requestself-request-42args-kwargs",
+ "text": "Ensures that the request object that is passed to the handler method is an instance of Request , rather than the usual Django HttpRequest . You won't typically need to override this method.",
+ "title": ".initialize_request(self, request, *args, **kwargs)"
+ },
+ {
+ "location": "/api-guide/views/#finalize_responseself-request-response-42args-kwargs",
+ "text": "Ensures that any Response object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation. You won't typically need to override this method.",
+ "title": ".finalize_response(self, request, response, *args, **kwargs)"
+ },
{
"location": "/api-guide/views/#function-based-views",
"text": "Saying [that Class based views] is always the superior solution is a mistake. Nick Coghlan REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than the usual Django HttpRequest ) and allows them to return a Response (instead of a Django HttpResponse ), and allow you to configure how the request is processed.",
@@ -597,9 +702,39 @@
},
{
"location": "/api-guide/generic-views/#genericapiview",
- "text": "This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views. Each of the concrete generic views provided is built by combining GenericAPIView , with one or more mixin classes. Attributes Basic settings : The following attributes control the basic view behavior. queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests. serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method. lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk' . Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value. lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field . Pagination : The following attributes are used to control pagination when used with list views. pagination_class - The pagination class that should be used when paginating list results. Defaults to the same value as the DEFAULT_PAGINATION_CLASS setting, which is 'rest_framework.pagination.PageNumberPagination' . Filtering : filter_backends - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the DEFAULT_FILTER_BACKENDS setting. Methods Base methods : get_queryset(self) Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the queryset attribute. This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests. May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request. For example: def get_queryset(self):\n user = self.request.user\n return user.accounts.all() get_object(self) Returns an object instance that should be used for detail views. Defaults to using the lookup_field parameter to filter the base queryset. May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg. For example: def get_object(self):\n queryset = self.get_queryset()\n filter = {}\n for field in self.multiple_lookup_fields:\n filter[field] = self.kwargs[field]\n\n obj = get_object_or_404(queryset, **filter)\n self.check_object_permissions(self.request, obj)\n return obj Note that if your API doesn't include any object level permissions, you may optionally exclude the self.check_object_permissions , and simply return the object from the get_object_or_404 lookup. filter_queryset(self, queryset) Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. For example: def filter_queryset(self, queryset):\n filter_backends = (CategoryFilter,)\n\n if 'geo_route' in self.request.query_params:\n filter_backends = (GeoRouteFilter, CategoryFilter)\n elif 'geo_point' in self.request.query_params:\n filter_backends = (GeoPointFilter, CategoryFilter)\n\n for backend in list(filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n return queryset get_serializer_class(self) Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute. May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users. For example: def get_serializer_class(self):\n if self.request.user.is_staff:\n return FullAccountSerializer\n return BasicAccountSerializer Save and deletion hooks : The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior. perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance. perform_update(self, serializer) - Called by UpdateModelMixin when saving an existing object instance. perform_destroy(self, instance) - Called by DestroyModelMixin when deleting an object instance. These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument. def perform_create(self, serializer):\n serializer.save(user=self.request.user) These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update. def perform_update(self, serializer):\n instance = serializer.save()\n send_email_confirmation(user=self.request.user, modified=instance) You can also use these hooks to provide additional validation, by raising a ValidationError() . This can be useful if you need some validation logic to apply at the point of database save. For example: def perform_create(self, serializer):\n queryset = SignupRequest.objects.filter(user=self.request.user)\n if queryset.exists():\n raise ValidationError('You have already signed up')\n serializer.save(user=self.request.user) Note : These methods replace the old-style version 2.x pre_save , post_save , pre_delete and post_delete methods, which are no longer available. Other methods : You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using GenericAPIView . get_serializer_context(self) - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including 'request' , 'view' and 'format' keys. get_serializer(self, instance=None, data=None, many=False, partial=False) - Returns a serializer instance. get_paginated_response(self, data) - Returns a paginated style Response object. paginate_queryset(self, queryset) - Paginate a queryset if required, either returning a page object, or None if pagination is not configured for this view. filter_queryset(self, queryset) - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.",
+ "text": "This class extends REST framework's APIView class, adding commonly required behavior for standard list and detail views. Each of the concrete generic views provided is built by combining GenericAPIView , with one or more mixin classes.",
"title": "GenericAPIView"
},
+ {
+ "location": "/api-guide/generic-views/#attributes",
+ "text": "Basic settings : The following attributes control the basic view behavior. queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests. serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method. lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk' . Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value. lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field . Pagination : The following attributes are used to control pagination when used with list views. pagination_class - The pagination class that should be used when paginating list results. Defaults to the same value as the DEFAULT_PAGINATION_CLASS setting, which is 'rest_framework.pagination.PageNumberPagination' . Filtering : filter_backends - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the DEFAULT_FILTER_BACKENDS setting.",
+ "title": "Attributes"
+ },
+ {
+ "location": "/api-guide/generic-views/#methods",
+ "text": "Base methods :",
+ "title": "Methods"
+ },
+ {
+ "location": "/api-guide/generic-views/#get_querysetself",
+ "text": "Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the queryset attribute. This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests. May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request. For example: def get_queryset(self):\n user = self.request.user\n return user.accounts.all()",
+ "title": "get_queryset(self)"
+ },
+ {
+ "location": "/api-guide/generic-views/#get_objectself",
+ "text": "Returns an object instance that should be used for detail views. Defaults to using the lookup_field parameter to filter the base queryset. May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg. For example: def get_object(self):\n queryset = self.get_queryset()\n filter = {}\n for field in self.multiple_lookup_fields:\n filter[field] = self.kwargs[field]\n\n obj = get_object_or_404(queryset, **filter)\n self.check_object_permissions(self.request, obj)\n return obj Note that if your API doesn't include any object level permissions, you may optionally exclude the self.check_object_permissions , and simply return the object from the get_object_or_404 lookup.",
+ "title": "get_object(self)"
+ },
+ {
+ "location": "/api-guide/generic-views/#filter_querysetself-queryset",
+ "text": "Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. For example: def filter_queryset(self, queryset):\n filter_backends = (CategoryFilter,)\n\n if 'geo_route' in self.request.query_params:\n filter_backends = (GeoRouteFilter, CategoryFilter)\n elif 'geo_point' in self.request.query_params:\n filter_backends = (GeoPointFilter, CategoryFilter)\n\n for backend in list(filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n return queryset",
+ "title": "filter_queryset(self, queryset)"
+ },
+ {
+ "location": "/api-guide/generic-views/#get_serializer_classself",
+ "text": "Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute. May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users. For example: def get_serializer_class(self):\n if self.request.user.is_staff:\n return FullAccountSerializer\n return BasicAccountSerializer Save and deletion hooks : The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior. perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance. perform_update(self, serializer) - Called by UpdateModelMixin when saving an existing object instance. perform_destroy(self, instance) - Called by DestroyModelMixin when deleting an object instance. These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument. def perform_create(self, serializer):\n serializer.save(user=self.request.user) These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update. def perform_update(self, serializer):\n instance = serializer.save()\n send_email_confirmation(user=self.request.user, modified=instance) You can also use these hooks to provide additional validation, by raising a ValidationError() . This can be useful if you need some validation logic to apply at the point of database save. For example: def perform_create(self, serializer):\n queryset = SignupRequest.objects.filter(user=self.request.user)\n if queryset.exists():\n raise ValidationError('You have already signed up')\n serializer.save(user=self.request.user) Note : These methods replace the old-style version 2.x pre_save , post_save , pre_delete and post_delete methods, which are no longer available. Other methods : You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using GenericAPIView . get_serializer_context(self) - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including 'request' , 'view' and 'format' keys. get_serializer(self, instance=None, data=None, many=False, partial=False) - Returns a serializer instance. get_paginated_response(self, data) - Returns a paginated style Response object. paginate_queryset(self, queryset) - Paginate a queryset if required, either returning a page object, or None if pagination is not configured for this view. filter_queryset(self, queryset) - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.",
+ "title": "get_serializer_class(self)"
+ },
{
"location": "/api-guide/generic-views/#mixins",
"text": "The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post() , directly. This allows for more flexible composition of behavior. The mixin classes can be imported from rest_framework.mixins .",
@@ -752,14 +887,24 @@
},
{
"location": "/api-guide/viewsets/#modelviewset",
- "text": "The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the ModelViewSet class are .list() , .retrieve() , .create() , .update() , .partial_update() , and .destroy() . Example Because ModelViewSet extends GenericAPIView , you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly] Note that you can use any of the standard attributes or method overrides provided by GenericAPIView . For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all() Note however that upon removal of the queryset property from your ViewSet , any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify the base_name kwarg as part of your router registration . Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.",
+ "text": "The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the ModelViewSet class are .list() , .retrieve() , .create() , .update() , .partial_update() , and .destroy() .",
"title": "ModelViewSet"
},
+ {
+ "location": "/api-guide/viewsets/#example_1",
+ "text": "Because ModelViewSet extends GenericAPIView , you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly] Note that you can use any of the standard attributes or method overrides provided by GenericAPIView . For example, to use a ViewSet that dynamically determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n A simple ViewSet for viewing and editing the accounts\n associated with the user.\n \"\"\"\n serializer_class = AccountSerializer\n permission_classes = [IsAccountAdminOrReadOnly]\n\n def get_queryset(self):\n return self.request.user.accounts.all() Note however that upon removal of the queryset property from your ViewSet , any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify the base_name kwarg as part of your router registration . Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.",
+ "title": "Example"
+ },
{
"location": "/api-guide/viewsets/#readonlymodelviewset",
- "text": "The ReadOnlyModelViewSet class also inherits from GenericAPIView . As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve() . Example As with ModelViewSet , you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A simple ViewSet for viewing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer Again, as with ModelViewSet , you can use any of the standard attributes and method overrides available to GenericAPIView .",
+ "text": "The ReadOnlyModelViewSet class also inherits from GenericAPIView . As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve() .",
"title": "ReadOnlyModelViewSet"
},
+ {
+ "location": "/api-guide/viewsets/#example_2",
+ "text": "As with ModelViewSet , you'll normally need to provide at least the queryset and serializer_class attributes. For example: class AccountViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"\n A simple ViewSet for viewing accounts.\n \"\"\"\n queryset = Account.objects.all()\n serializer_class = AccountSerializer Again, as with ModelViewSet , you can use any of the standard attributes and method overrides available to GenericAPIView .",
+ "title": "Example"
+ },
{
"location": "/api-guide/viewsets/#custom-viewset-base-classes",
"text": "You may need to provide custom ViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way.",
@@ -782,9 +927,19 @@
},
{
"location": "/api-guide/routers/#usage",
- "text": "Here's an example of a simple URL conf, that uses SimpleRouter . from rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls There are two mandatory arguments to the register() method: prefix - The URL prefix to use for this set of routes. viewset - The viewset class. Optionally, you may also specify an additional argument: base_name - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set base_name when registering the viewset. The example above would generate the following URL patterns: URL pattern: ^users/$ Name: 'user-list' URL pattern: ^users/{pk}/$ Name: 'user-detail' URL pattern: ^accounts/$ Name: 'account-list' URL pattern: ^accounts/{pk}/$ Name: 'account-detail' Note : The base_name argument is used to specify the initial part of the view name pattern. In the example above, that's the user or account part. Typically you won't need to specify the base_name argument, but if you have a viewset where you've defined a custom get_queryset method, then the viewset may not have a .queryset attribute set. If you try to register that viewset you'll see an error like this: 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. This means you'll need to explicitly set the base_name argument when registering the viewset, as it could not be automatically determined from the model name. Using include with routers The .urls attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs. For example, you can append router.urls to a list of existing views\u2026 router = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls Alternatively you can use Django's include function, like so\u2026 urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^', include(router.urls)),\n] Router URL patterns can also be namespaces. urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include(router.urls, namespace='api')),\n] If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as view_name='api:user-detail' for serializer fields hyperlinked to the user detail view. Extra link and actions Any methods on the viewset decorated with @detail_route or @list_route will also be routed.\nFor example, given a method like this on the UserViewSet class: from myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import detail_route\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ... The following URL pattern would additionally be generated: URL pattern: ^users/{pk}/set_password/$ Name: 'user-set-password' If you do not want to use the default URL generated for your custom action, you can instead use the url_path parameter to customize it. For example, if you want to change the URL for our custom action to ^users/{pk}/change-password/$ , you could write: from myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import detail_route\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_path='change-password')\n def set_password(self, request, pk=None):\n ... The above example would now generate the following URL pattern: URL pattern: ^users/{pk}/change-password/$ Name: 'user-change-password' For more information see the viewset documentation on marking extra actions for routing .",
+ "text": "Here's an example of a simple URL conf, that uses SimpleRouter . from rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\nurlpatterns = router.urls There are two mandatory arguments to the register() method: prefix - The URL prefix to use for this set of routes. viewset - The viewset class. Optionally, you may also specify an additional argument: base_name - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set base_name when registering the viewset. The example above would generate the following URL patterns: URL pattern: ^users/$ Name: 'user-list' URL pattern: ^users/{pk}/$ Name: 'user-detail' URL pattern: ^accounts/$ Name: 'account-list' URL pattern: ^accounts/{pk}/$ Name: 'account-detail' Note : The base_name argument is used to specify the initial part of the view name pattern. In the example above, that's the user or account part. Typically you won't need to specify the base_name argument, but if you have a viewset where you've defined a custom get_queryset method, then the viewset may not have a .queryset attribute set. If you try to register that viewset you'll see an error like this: 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. This means you'll need to explicitly set the base_name argument when registering the viewset, as it could not be automatically determined from the model name.",
"title": "Usage"
},
+ {
+ "location": "/api-guide/routers/#using-include-with-routers",
+ "text": "The .urls attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs. For example, you can append router.urls to a list of existing views\u2026 router = routers.SimpleRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'accounts', AccountViewSet)\n\nurlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n]\n\nurlpatterns += router.urls Alternatively you can use Django's include function, like so\u2026 urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^', include(router.urls)),\n] Router URL patterns can also be namespaces. urlpatterns = [\n url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),\n url(r'^api/', include(router.urls, namespace='api')),\n] If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as view_name='api:user-detail' for serializer fields hyperlinked to the user detail view.",
+ "title": "Using include with routers"
+ },
+ {
+ "location": "/api-guide/routers/#extra-link-and-actions",
+ "text": "Any methods on the viewset decorated with @detail_route or @list_route will also be routed.\nFor example, given a method like this on the UserViewSet class: from myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import detail_route\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])\n def set_password(self, request, pk=None):\n ... The following URL pattern would additionally be generated: URL pattern: ^users/{pk}/set_password/$ Name: 'user-set-password' If you do not want to use the default URL generated for your custom action, you can instead use the url_path parameter to customize it. For example, if you want to change the URL for our custom action to ^users/{pk}/change-password/$ , you could write: from myapp.permissions import IsAdminOrIsSelf\nfrom rest_framework.decorators import detail_route\n\nclass UserViewSet(ModelViewSet):\n ...\n\n @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_path='change-password')\n def set_password(self, request, pk=None):\n ... The above example would now generate the following URL pattern: URL pattern: ^users/{pk}/change-password/$ Name: 'user-change-password' For more information see the viewset documentation on marking extra actions for routing .",
+ "title": "Extra link and actions"
+ },
{
"location": "/api-guide/routers/#api-guide",
"text": "",
@@ -842,7 +997,7 @@
},
{
"location": "/api-guide/parsers/",
- "text": "Parsers\n\n\n\n\nMachine interacting web services tend to use more\nstructured formats for sending data than form-encoded, since they're\nsending more complex data than simple forms\n\n\n Malcom Tredinnick, \nDjango developers group\n\n\n\n\nREST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.\n\n\nHow the parser is determined\n\n\nThe set of valid parsers for a view is always defined as a list of classes. When \nrequest.data\n is accessed, REST framework will examine the \nContent-Type\n header on the incoming request, and determine which parser to use to parse the request content.\n\n\n\n\nNote\n: When developing client applications always remember to make sure you're setting the \nContent-Type\n header when sending data in an HTTP request.\n\n\nIf you don't set the content type, most clients will default to using \n'application/x-www-form-urlencoded'\n, which may not be what you wanted.\n\n\nAs an example, if you are sending \njson\n encoded data using jQuery with the \n.ajax() method\n, you should make sure to include the \ncontentType: 'application/json'\n setting.\n\n\n\n\nSetting the parsers\n\n\nThe default set of parsers may be set globally, using the \nDEFAULT_PARSER_CLASSES\n setting. For example, the following settings would allow only requests with \nJSON\n content, instead of the default of JSON or form data.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework.parsers.JSONParser',\n )\n}\n\n\n\nYou can also set the parsers used for an individual view, or viewset,\nusing the \nAPIView\n class based views.\n\n\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n parser_classes = (JSONParser,)\n\n def post(self, request, format=None):\n return Response({'received data': request.data})\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.decorators import parser_classes\n\n@api_view(['POST'])\n@parser_classes((JSONParser,))\ndef example_view(request, format=None):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n return Response({'received data': request.data})\n\n\n\n\n\nAPI Reference\n\n\nJSONParser\n\n\nParses \nJSON\n request content.\n\n\n.media_type\n: \napplication/json\n\n\nFormParser\n\n\nParses HTML form content. \nrequest.data\n will be populated with a \nQueryDict\n of data.\n\n\nYou will typically want to use both \nFormParser\n and \nMultiPartParser\n together in order to fully support HTML form data.\n\n\n.media_type\n: \napplication/x-www-form-urlencoded\n\n\nMultiPartParser\n\n\nParses multipart HTML form content, which supports file uploads. Both \nrequest.data\n will be populated with a \nQueryDict\n.\n\n\nYou will typically want to use both \nFormParser\n and \nMultiPartParser\n together in order to fully support HTML form data.\n\n\n.media_type\n: \nmultipart/form-data\n\n\nFileUploadParser\n\n\nParses raw file upload content. The \nrequest.data\n property will be a dictionary with a single key \n'file'\n containing the uploaded file.\n\n\nIf the view used with \nFileUploadParser\n is called with a \nfilename\n URL keyword argument, then that argument will be used as the filename. If it is called without a \nfilename\n URL keyword argument, then the client must set the filename in the \nContent-Disposition\n HTTP header. For example \nContent-Disposition: attachment; filename=upload.jpg\n.\n\n\n.media_type\n: \n*/*\n\n\nNotes:\n\n\n\n\nThe \nFileUploadParser\n is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the \nMultiPartParser\n parser instead.\n\n\nSince this parser's \nmedia_type\n matches any content type, \nFileUploadParser\n should generally be the only parser set on an API view.\n\n\nFileUploadParser\n respects Django's standard \nFILE_UPLOAD_HANDLERS\n setting, and the \nrequest.upload_handlers\n attribute. See the \nDjango documentation\n for more details.\n\n\n\n\nBasic usage example:\n\n\nclass FileUploadView(views.APIView):\n parser_classes = (FileUploadParser,)\n\n def put(self, request, filename, format=None):\n file_obj = request.data['file']\n # ...\n # do some stuff with uploaded file\n # ...\n return Response(status=204)\n\n\n\n\n\nCustom parsers\n\n\nTo implement a custom parser, you should override \nBaseParser\n, set the \n.media_type\n property, and implement the \n.parse(self, stream, media_type, parser_context)\n method.\n\n\nThe method should return the data that will be used to populate the \nrequest.data\n property.\n\n\nThe arguments passed to \n.parse()\n are:\n\n\nstream\n\n\nA stream-like object representing the body of the request.\n\n\nmedia_type\n\n\nOptional. If provided, this is the media type of the incoming request content.\n\n\nDepending on the request's \nContent-Type:\n header, this may be more specific than the renderer's \nmedia_type\n attribute, and may include media type parameters. For example \n\"text/plain; charset=utf-8\"\n.\n\n\nparser_context\n\n\nOptional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.\n\n\nBy default this will include the following keys: \nview\n, \nrequest\n, \nargs\n, \nkwargs\n.\n\n\nExample\n\n\nThe following is an example plaintext parser that will populate the \nrequest.data\n property with a string representing the body of the request.\n\n\nclass PlainTextParser(BaseParser):\n \"\"\"\n Plain text parser.\n \"\"\"\n media_type = 'text/plain'\n\n def parse(self, stream, media_type=None, parser_context=None):\n \"\"\"\n Simply return a string representing the body of the request.\n \"\"\"\n return stream.read()\n\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nYAML\n\n\nREST framework YAML\n provides \nYAML\n parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation \n configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-yaml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}\n\n\n\nXML\n\n\nREST Framework XML\n provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation \n configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-xml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}\n\n\n\nMessagePack\n\n\nMessagePack\n is a fast, efficient binary serialization format. \nJuan Riaza\n maintains the \ndjangorestframework-msgpack\n package which provides MessagePack renderer and parser support for REST framework.\n\n\nCamelCase JSON\n\n\ndjangorestframework-camel-case\n provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by \nVitaly Babiy\n.",
+ "text": "Parsers\n\n\n\n\nMachine interacting web services tend to use more\nstructured formats for sending data than form-encoded, since they're\nsending more complex data than simple forms\n\n\n Malcom Tredinnick, \nDjango developers group\n\n\n\n\nREST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.\n\n\nHow the parser is determined\n\n\nThe set of valid parsers for a view is always defined as a list of classes. When \nrequest.data\n is accessed, REST framework will examine the \nContent-Type\n header on the incoming request, and determine which parser to use to parse the request content.\n\n\n\n\nNote\n: When developing client applications always remember to make sure you're setting the \nContent-Type\n header when sending data in an HTTP request.\n\n\nIf you don't set the content type, most clients will default to using \n'application/x-www-form-urlencoded'\n, which may not be what you wanted.\n\n\nAs an example, if you are sending \njson\n encoded data using jQuery with the \n.ajax() method\n, you should make sure to include the \ncontentType: 'application/json'\n setting.\n\n\n\n\nSetting the parsers\n\n\nThe default set of parsers may be set globally, using the \nDEFAULT_PARSER_CLASSES\n setting. For example, the following settings would allow only requests with \nJSON\n content, instead of the default of JSON or form data.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework.parsers.JSONParser',\n )\n}\n\n\n\nYou can also set the parsers used for an individual view, or viewset,\nusing the \nAPIView\n class based views.\n\n\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n parser_classes = (JSONParser,)\n\n def post(self, request, format=None):\n return Response({'received data': request.data})\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.decorators import parser_classes\n\n@api_view(['POST'])\n@parser_classes((JSONParser,))\ndef example_view(request, format=None):\n \"\"\"\n A view that can accept POST requests with JSON content.\n \"\"\"\n return Response({'received data': request.data})\n\n\n\n\n\nAPI Reference\n\n\nJSONParser\n\n\nParses \nJSON\n request content.\n\n\n.media_type\n: \napplication/json\n\n\nFormParser\n\n\nParses HTML form content. \nrequest.data\n will be populated with a \nQueryDict\n of data.\n\n\nYou will typically want to use both \nFormParser\n and \nMultiPartParser\n together in order to fully support HTML form data.\n\n\n.media_type\n: \napplication/x-www-form-urlencoded\n\n\nMultiPartParser\n\n\nParses multipart HTML form content, which supports file uploads. Both \nrequest.data\n will be populated with a \nQueryDict\n.\n\n\nYou will typically want to use both \nFormParser\n and \nMultiPartParser\n together in order to fully support HTML form data.\n\n\n.media_type\n: \nmultipart/form-data\n\n\nFileUploadParser\n\n\nParses raw file upload content. The \nrequest.data\n property will be a dictionary with a single key \n'file'\n containing the uploaded file.\n\n\nIf the view used with \nFileUploadParser\n is called with a \nfilename\n URL keyword argument, then that argument will be used as the filename.\n\n\nIf it is called without a \nfilename\n URL keyword argument, then the client must set the filename in the \nContent-Disposition\n HTTP header. For example \nContent-Disposition: attachment; filename=upload.jpg\n.\n\n\n.media_type\n: \n*/*\n\n\nNotes:\n\n\n\n\nThe \nFileUploadParser\n is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the \nMultiPartParser\n parser instead.\n\n\nSince this parser's \nmedia_type\n matches any content type, \nFileUploadParser\n should generally be the only parser set on an API view.\n\n\nFileUploadParser\n respects Django's standard \nFILE_UPLOAD_HANDLERS\n setting, and the \nrequest.upload_handlers\n attribute. See the \nDjango documentation\n for more details.\n\n\n\n\nBasic usage example:\n\n\n# views.py\nclass FileUploadView(views.APIView):\n parser_classes = (FileUploadParser,)\n\n def put(self, request, filename, format=None):\n file_obj = request.data['file']\n # ...\n # do some stuff with uploaded file\n # ...\n return Response(status=204)\n\n# urls.py\nurlpatterns = [\n # ...\n url(r'^upload/(?P\nfilename\n[^/]+)$', FileUploadView.as_view())\n]\n\n\n\n\n\nCustom parsers\n\n\nTo implement a custom parser, you should override \nBaseParser\n, set the \n.media_type\n property, and implement the \n.parse(self, stream, media_type, parser_context)\n method.\n\n\nThe method should return the data that will be used to populate the \nrequest.data\n property.\n\n\nThe arguments passed to \n.parse()\n are:\n\n\nstream\n\n\nA stream-like object representing the body of the request.\n\n\nmedia_type\n\n\nOptional. If provided, this is the media type of the incoming request content.\n\n\nDepending on the request's \nContent-Type:\n header, this may be more specific than the renderer's \nmedia_type\n attribute, and may include media type parameters. For example \n\"text/plain; charset=utf-8\"\n.\n\n\nparser_context\n\n\nOptional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.\n\n\nBy default this will include the following keys: \nview\n, \nrequest\n, \nargs\n, \nkwargs\n.\n\n\nExample\n\n\nThe following is an example plaintext parser that will populate the \nrequest.data\n property with a string representing the body of the request.\n\n\nclass PlainTextParser(BaseParser):\n \"\"\"\n Plain text parser.\n \"\"\"\n media_type = 'text/plain'\n\n def parse(self, stream, media_type=None, parser_context=None):\n \"\"\"\n Simply return a string representing the body of the request.\n \"\"\"\n return stream.read()\n\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nYAML\n\n\nREST framework YAML\n provides \nYAML\n parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation \n configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-yaml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}\n\n\n\nXML\n\n\nREST Framework XML\n provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.\n\n\nInstallation \n configuration\n\n\nInstall using pip.\n\n\n$ pip install djangorestframework-xml\n\n\n\nModify your REST framework settings.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}\n\n\n\nMessagePack\n\n\nMessagePack\n is a fast, efficient binary serialization format. \nJuan Riaza\n maintains the \ndjangorestframework-msgpack\n package which provides MessagePack renderer and parser support for REST framework.\n\n\nCamelCase JSON\n\n\ndjangorestframework-camel-case\n provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by \nVitaly Babiy\n.",
"title": "Parsers"
},
{
@@ -882,14 +1037,39 @@
},
{
"location": "/api-guide/parsers/#fileuploadparser",
- "text": "Parses raw file upload content. The request.data property will be a dictionary with a single key 'file' containing the uploaded file. If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg . .media_type : */* Notes: The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser parser instead. Since this parser's media_type matches any content type, FileUploadParser should generally be the only parser set on an API view. FileUploadParser respects Django's standard FILE_UPLOAD_HANDLERS setting, and the request.upload_handlers attribute. See the Django documentation for more details. Basic usage example: class FileUploadView(views.APIView):\n parser_classes = (FileUploadParser,)\n\n def put(self, request, filename, format=None):\n file_obj = request.data['file']\n # ...\n # do some stuff with uploaded file\n # ...\n return Response(status=204)",
+ "text": "Parses raw file upload content. The request.data property will be a dictionary with a single key 'file' containing the uploaded file. If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg . .media_type : */*",
"title": "FileUploadParser"
},
+ {
+ "location": "/api-guide/parsers/#notes",
+ "text": "The FileUploadParser is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the MultiPartParser parser instead. Since this parser's media_type matches any content type, FileUploadParser should generally be the only parser set on an API view. FileUploadParser respects Django's standard FILE_UPLOAD_HANDLERS setting, and the request.upload_handlers attribute. See the Django documentation for more details.",
+ "title": "Notes:"
+ },
+ {
+ "location": "/api-guide/parsers/#basic-usage-example",
+ "text": "# views.py\nclass FileUploadView(views.APIView):\n parser_classes = (FileUploadParser,)\n\n def put(self, request, filename, format=None):\n file_obj = request.data['file']\n # ...\n # do some stuff with uploaded file\n # ...\n return Response(status=204)\n\n# urls.py\nurlpatterns = [\n # ...\n url(r'^upload/(?P filename [^/]+)$', FileUploadView.as_view())\n]",
+ "title": "Basic usage example:"
+ },
{
"location": "/api-guide/parsers/#custom-parsers",
- "text": "To implement a custom parser, you should override BaseParser , set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method. The method should return the data that will be used to populate the request.data property. The arguments passed to .parse() are: stream A stream-like object representing the body of the request. media_type Optional. If provided, this is the media type of the incoming request content. Depending on the request's Content-Type: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example \"text/plain; charset=utf-8\" . parser_context Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. By default this will include the following keys: view , request , args , kwargs .",
+ "text": "To implement a custom parser, you should override BaseParser , set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method. The method should return the data that will be used to populate the request.data property. The arguments passed to .parse() are:",
"title": "Custom parsers"
},
+ {
+ "location": "/api-guide/parsers/#stream",
+ "text": "A stream-like object representing the body of the request.",
+ "title": "stream"
+ },
+ {
+ "location": "/api-guide/parsers/#media_type",
+ "text": "Optional. If provided, this is the media type of the incoming request content. Depending on the request's Content-Type: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example \"text/plain; charset=utf-8\" .",
+ "title": "media_type"
+ },
+ {
+ "location": "/api-guide/parsers/#parser_context",
+ "text": "Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. By default this will include the following keys: view , request , args , kwargs .",
+ "title": "parser_context"
+ },
{
"location": "/api-guide/parsers/#example",
"text": "The following is an example plaintext parser that will populate the request.data property with a string representing the body of the request. class PlainTextParser(BaseParser):\n \"\"\"\n Plain text parser.\n \"\"\"\n media_type = 'text/plain'\n\n def parse(self, stream, media_type=None, parser_context=None):\n \"\"\"\n Simply return a string representing the body of the request.\n \"\"\"\n return stream.read()",
@@ -902,14 +1082,24 @@
},
{
"location": "/api-guide/parsers/#yaml",
- "text": "REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation configuration Install using pip. $ pip install djangorestframework-yaml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}",
+ "text": "REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.",
"title": "YAML"
},
+ {
+ "location": "/api-guide/parsers/#installation-configuration",
+ "text": "Install using pip. $ pip install djangorestframework-yaml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}",
+ "title": "Installation & configuration"
+ },
{
"location": "/api-guide/parsers/#xml",
- "text": "REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation configuration Install using pip. $ pip install djangorestframework-xml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}",
+ "text": "REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.",
"title": "XML"
},
+ {
+ "location": "/api-guide/parsers/#installation-configuration_1",
+ "text": "Install using pip. $ pip install djangorestframework-xml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}",
+ "title": "Installation & configuration"
+ },
{
"location": "/api-guide/parsers/#messagepack",
"text": "MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework.",
@@ -967,9 +1157,14 @@
},
{
"location": "/api-guide/renderers/#browsableapirenderer",
- "text": "Renders data into HTML for the Browsable API: This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. .media_type : text/html .format : '.api' .charset : utf-8 .template : 'rest_framework/api.html' Customizing BrowsableAPIRenderer By default the response content will be rendered with the highest priority renderer apart from BrowsableAPIRenderer . If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the get_default_renderer() method. For example: class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):\n def get_default_renderer(self, view):\n return JSONRenderer()",
+ "text": "Renders data into HTML for the Browsable API: This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. .media_type : text/html .format : '.api' .charset : utf-8 .template : 'rest_framework/api.html'",
"title": "BrowsableAPIRenderer"
},
+ {
+ "location": "/api-guide/renderers/#customizing-browsableapirenderer",
+ "text": "By default the response content will be rendered with the highest priority renderer apart from BrowsableAPIRenderer . If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the get_default_renderer() method. For example: class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):\n def get_default_renderer(self, view):\n return JSONRenderer()",
+ "title": "Customizing BrowsableAPIRenderer"
+ },
{
"location": "/api-guide/renderers/#adminrenderer",
"text": "Renders data into HTML for an admin-like display: This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data. Note that views that have nested or list serializers for their input won't work well with the AdminRenderer , as the HTML forms are unable to properly support them. Note : The AdminRenderer is only able to include links to detail pages when a properly configured URL_FIELD_NAME ( url by default) attribute is present in the data. For HyperlinkedModelSerializer this will be the case, but for ModelSerializer or plain Serializer classes you'll need to make sure to include the field explicitly. For example here we use models get_absolute_url method: class AccountSerializer(serializers.ModelSerializer):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n\n class Meta:\n model = Account .media_type : text/html .format : '.admin' .charset : utf-8 .template : 'rest_framework/admin.html'",
@@ -987,9 +1182,24 @@
},
{
"location": "/api-guide/renderers/#custom-renderers",
- "text": "To implement a custom renderer, you should override BaseRenderer , set the .media_type and .format properties, and implement the .render(self, data, media_type=None, renderer_context=None) method. The method should return a bytestring, which will be used as the body of the HTTP response. The arguments passed to the .render() method are: data The request data, as set by the Response() instantiation. media_type=None Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. Depending on the client's Accept: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example \"application/json; nested=true\" . renderer_context=None Optional. If provided, this is a dictionary of contextual information provided by the view. By default this will include the following keys: view , request , response , args , kwargs .",
+ "text": "To implement a custom renderer, you should override BaseRenderer , set the .media_type and .format properties, and implement the .render(self, data, media_type=None, renderer_context=None) method. The method should return a bytestring, which will be used as the body of the HTTP response. The arguments passed to the .render() method are:",
"title": "Custom renderers"
},
+ {
+ "location": "/api-guide/renderers/#data",
+ "text": "The request data, as set by the Response() instantiation.",
+ "title": "data"
+ },
+ {
+ "location": "/api-guide/renderers/#media_typenone",
+ "text": "Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. Depending on the client's Accept: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example \"application/json; nested=true\" .",
+ "title": "media_type=None"
+ },
+ {
+ "location": "/api-guide/renderers/#renderer_contextnone",
+ "text": "Optional. If provided, this is a dictionary of contextual information provided by the view. By default this will include the following keys: view , request , response , args , kwargs .",
+ "title": "renderer_context=None"
+ },
{
"location": "/api-guide/renderers/#example",
"text": "The following is an example plaintext renderer that will return a response with the data parameter as the content of the response. from django.utils.encoding import smart_unicode\nfrom rest_framework import renderers\n\n\nclass PlainTextRenderer(renderers.BaseRenderer):\n media_type = 'text/plain'\n format = 'txt'\n\n def render(self, data, media_type=None, renderer_context=None):\n return data.encode(self.charset)",
@@ -1032,19 +1242,34 @@
},
{
"location": "/api-guide/renderers/#yaml",
- "text": "REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation configuration Install using pip. $ pip install djangorestframework-yaml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}",
+ "text": "REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.",
"title": "YAML"
},
+ {
+ "location": "/api-guide/renderers/#installation-configuration",
+ "text": "Install using pip. $ pip install djangorestframework-yaml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_yaml.parsers.YAMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_yaml.renderers.YAMLRenderer',\n ),\n}",
+ "title": "Installation & configuration"
+ },
{
"location": "/api-guide/renderers/#xml",
- "text": "REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Installation configuration Install using pip. $ pip install djangorestframework-xml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}",
+ "text": "REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.",
"title": "XML"
},
+ {
+ "location": "/api-guide/renderers/#installation-configuration_1",
+ "text": "Install using pip. $ pip install djangorestframework-xml Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework_xml.parsers.XMLParser',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_xml.renderers.XMLRenderer',\n ),\n}",
+ "title": "Installation & configuration"
+ },
{
"location": "/api-guide/renderers/#jsonp",
- "text": "REST framework JSONP provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Warning : If you require cross-domain AJAX requests, you should generally be using the more modern approach of CORS as an alternative to JSONP . See the CORS documentation for more details. The jsonp approach is essentially a browser hack, and is only appropriate for globally readable API endpoints , where GET requests are unauthenticated and do not require any user permissions. Installation configuration Install using pip. $ pip install djangorestframework-jsonp Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_jsonp.renderers.JSONPRenderer',\n ),\n}",
+ "text": "REST framework JSONP provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. Warning : If you require cross-domain AJAX requests, you should generally be using the more modern approach of CORS as an alternative to JSONP . See the CORS documentation for more details. The jsonp approach is essentially a browser hack, and is only appropriate for globally readable API endpoints , where GET requests are unauthenticated and do not require any user permissions.",
"title": "JSONP"
},
+ {
+ "location": "/api-guide/renderers/#installation-configuration_2",
+ "text": "Install using pip. $ pip install djangorestframework-jsonp Modify your REST framework settings. REST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework_jsonp.renderers.JSONPRenderer',\n ),\n}",
+ "title": "Installation & configuration"
+ },
{
"location": "/api-guide/renderers/#messagepack",
"text": "MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework.",
@@ -1077,7 +1302,7 @@
},
{
"location": "/api-guide/serializers/",
- "text": "Serializers\n\n\n\n\nExpanding the usefulness of the serializers is something that we would\nlike to address. However, it's not a trivial problem, and it\nwill take some serious design work.\n\n\n Russell Keith-Magee, \nDjango users group\n\n\n\n\nSerializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into \nJSON\n, \nXML\n or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.\n\n\nThe serializers in REST framework work very similarly to Django's \nForm\n and \nModelForm\n classes. We provide a \nSerializer\n class which gives you a powerful, generic way to control the output of your responses, as well as a \nModelSerializer\n class which provides a useful shortcut for creating serializers that deal with model instances and querysets.\n\n\nDeclaring Serializers\n\n\nLet's start by creating a simple object we can use for example purposes:\n\n\nfrom datetime import datetime\n\nclass Comment(object):\n def __init__(self, email, content, created=None):\n self.email = email\n self.content = content\n self.created = created or datetime.now()\n\ncomment = Comment(email='leila@example.com', content='foo bar')\n\n\n\nWe'll declare a serializer that we can use to serialize and deserialize data that corresponds to \nComment\n objects.\n\n\nDeclaring a serializer looks very similar to declaring a form:\n\n\nfrom rest_framework import serializers\n\nclass CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nSerializing objects\n\n\nWe can now use \nCommentSerializer\n to serialize a comment, or list of comments. Again, using the \nSerializer\n class looks a lot like using a \nForm\n class.\n\n\nserializer = CommentSerializer(comment)\nserializer.data\n# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into \njson\n.\n\n\nfrom rest_framework.renderers import JSONRenderer\n\njson = JSONRenderer().render(serializer.data)\njson\n# b'{\"email\":\"leila@example.com\",\"content\":\"foo bar\",\"created\":\"2016-01-27T15:17:10.375877\"}'\n\n\n\nDeserializing objects\n\n\nDeserialization is similar. First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\nfrom rest_framework.parsers import JSONParser\n\nstream = BytesIO(json)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a dictionary of validated data.\n\n\nserializer = CommentSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}\n\n\n\nSaving instances\n\n\nIf we want to be able to return complete object instances based on the validated data we need to implement one or both of the \n.create()\n and \nupdate()\n methods. For example:\n\n\nclass CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n def create(self, validated_data):\n return Comment(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n return instance\n\n\n\nIf your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if \nComment\n was a Django model, the methods might look like this:\n\n\n def create(self, validated_data):\n return Comment.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n instance.save()\n return instance\n\n\n\nNow when deserializing data, we can call \n.save()\n to return an object instance, based on the validated data.\n\n\ncomment = serializer.save()\n\n\n\nCalling \n.save()\n will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:\n\n\n# .save() will create a new instance.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data)\n\n\n\nBoth the \n.create()\n and \n.update()\n methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.\n\n\nPassing additional attributes to \n.save()\n\n\nSometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.\n\n\nYou can do so by including additional keyword arguments when calling \n.save()\n. For example:\n\n\nserializer.save(owner=request.user)\n\n\n\nAny additional keyword arguments will be included in the \nvalidated_data\n argument when \n.create()\n or \n.update()\n are called.\n\n\nOverriding \n.save()\n directly.\n\n\nIn some cases the \n.create()\n and \n.update()\n method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.\n\n\nIn these cases you might instead choose to override \n.save()\n directly, as being more readable and meaningful.\n\n\nFor example:\n\n\nclass ContactForm(serializers.Serializer):\n email = serializers.EmailField()\n message = serializers.CharField()\n\n def save(self):\n email = self.validated_data['email']\n message = self.validated_data['message']\n send_email(from=email, message=message)\n\n\n\nNote that in the case above we're now having to access the serializer \n.validated_data\n property directly.\n\n\nValidation\n\n\nWhen deserializing data, you always need to call \nis_valid()\n before attempting to access the validated data, or save an object instance. If any validation errors occur, the \n.errors\n property will contain a dictionary representing the resulting error messages. For example:\n\n\nserializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}\n\n\n\nEach key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The \nnon_field_errors\n key may also be present, and will list any general validation errors. The name of the \nnon_field_errors\n key may be customized using the \nNON_FIELD_ERRORS_KEY\n REST framework setting.\n\n\nWhen deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.\n\n\nRaising an exception on invalid data\n\n\nThe \n.is_valid()\n method takes an optional \nraise_exception\n flag that will cause it to raise a \nserializers.ValidationError\n exception if there are validation errors.\n\n\nThese exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return \nHTTP 400 Bad Request\n responses by default.\n\n\n# Return a 400 response if the data was invalid.\nserializer.is_valid(raise_exception=True)\n\n\n\nField-level validation\n\n\nYou can specify custom field-level validation by adding \n.validate_\nfield_name\n methods to your \nSerializer\n subclass. These are similar to the \n.clean_\nfield_name\n methods on Django forms.\n\n\nThese methods take a single argument, which is the field value that requires validation.\n\n\nYour \nvalidate_\nfield_name\n methods should return the validated value or raise a \nserializers.ValidationError\n. For example:\n\n\nfrom rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n title = serializers.CharField(max_length=100)\n content = serializers.CharField()\n\n def validate_title(self, value):\n \"\"\"\n Check that the blog post is about Django.\n \"\"\"\n if 'django' not in value.lower():\n raise serializers.ValidationError(\"Blog post is not about Django\")\n return value\n\n\n\n\n\nNote:\n If your \nfield_name\n is declared on your serializer with the parameter \nrequired=False\n then this validation step will not take place if the field is not included.\n\n\n\n\nObject-level validation\n\n\nTo do any other validation that requires access to multiple fields, add a method called \n.validate()\n to your \nSerializer\n subclass. This method takes a single argument, which is a dictionary of field values. It should raise a \nValidationError\n if necessary, or just return the validated values. For example:\n\n\nfrom rest_framework import serializers\n\nclass EventSerializer(serializers.Serializer):\n description = serializers.CharField(max_length=100)\n start = serializers.DateTimeField()\n finish = serializers.DateTimeField()\n\n def validate(self, data):\n \"\"\"\n Check that the start is before the stop.\n \"\"\"\n if data['start'] \n data['finish']:\n raise serializers.ValidationError(\"finish must occur after start\")\n return data\n\n\n\nValidators\n\n\nIndividual fields on a serializer can include validators, by declaring them on the field instance, for example:\n\n\ndef multiple_of_ten(value):\n if value % 10 != 0:\n raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n score = IntegerField(validators=[multiple_of_ten])\n ...\n\n\n\nSerializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner \nMeta\n class, like so:\n\n\nclass EventSerializer(serializers.Serializer):\n name = serializers.CharField()\n room_number = serializers.IntegerField(choices=[101, 102, 103, 201])\n date = serializers.DateField()\n\n class Meta:\n # Each room only has one event per day.\n validators = UniqueTogetherValidator(\n queryset=Event.objects.all(),\n fields=['room_number', 'date']\n )\n\n\n\nFor more information see the \nvalidators documentation\n.\n\n\nAccessing the initial data and instance\n\n\nWhen passing an initial object or queryset to a serializer instance, the object will be made available as \n.instance\n. If no initial object is passed then the \n.instance\n attribute will be \nNone\n.\n\n\nWhen passing data to a serializer instance, the unmodified data will be made available as \n.initial_data\n. If the data keyword argument is not passed then the \n.initial_data\n attribute will not exist.\n\n\nPartial updates\n\n\nBy default, serializers must be passed values for all required fields or they will raise validation errors. You can use the \npartial\n argument in order to allow partial updates.\n\n\n# Update `comment` with partial data\nserializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)\n\n\n\nDealing with nested objects\n\n\nThe previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.\n\n\nThe \nSerializer\n class is itself a type of \nField\n, and can be used to represent relationships where one object type is nested inside another.\n\n\nclass UserSerializer(serializers.Serializer):\n email = serializers.EmailField()\n username = serializers.CharField(max_length=100)\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nIf a nested representation may optionally accept the \nNone\n value you should pass the \nrequired=False\n flag to the nested serializer.\n\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer(required=False) # May be an anonymous user.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nSimilarly if a nested representation should be a list of items, you should pass the \nmany=True\n flag to the nested serialized.\n\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer(required=False)\n edits = EditItemSerializer(many=True) # A nested list of 'edit' items.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nWritable nested representations\n\n\nWhen dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object.\n\n\nserializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}\n\n\n\nSimilarly, the \n.validated_data\n property will include nested data structures.\n\n\nWriting \n.create()\n methods for nested representations\n\n\nIf you're supporting writable nested representations you'll need to write \n.create()\n or \n.update()\n methods that handle saving multiple objects.\n\n\nThe following example demonstrates how you might handle creating a user with a nested profile object.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n\n\n\nWriting \n.update()\n methods for nested representations\n\n\nFor updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is \nNone\n, or not provided, which of the following should occur?\n\n\n\n\nSet the relationship to \nNULL\n in the database.\n\n\nDelete the associated instance.\n\n\nIgnore the data and leave the instance as it is.\n\n\nRaise a validation error.\n\n\n\n\nHere's an example for an \nupdate()\n method on our previous \nUserSerializer\n class.\n\n\n def update(self, instance, validated_data):\n profile_data = validated_data.pop('profile')\n # Unless the application properly enforces that this field is\n # always set, the follow could raise a `DoesNotExist`, which\n # would need to be handled.\n profile = instance.profile\n\n instance.username = validated_data.get('username', instance.username)\n instance.email = validated_data.get('email', instance.email)\n instance.save()\n\n profile.is_premium_member = profile_data.get(\n 'is_premium_member',\n profile.is_premium_member\n )\n profile.has_support_contract = profile_data.get(\n 'has_support_contract',\n profile.has_support_contract\n )\n profile.save()\n\n return instance\n\n\n\nBecause the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default \nModelSerializer\n \n.create()\n and \n.update()\n methods do not include support for writable nested representations.\n\n\nIt is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.\n\n\nHandling saving related instances in model manager classes\n\n\nAn alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.\n\n\nFor example, suppose we wanted to ensure that \nUser\n instances and \nProfile\n instances are always created together as a pair. We might write a custom manager class that looks something like this:\n\n\nclass UserManager(models.Manager):\n ...\n\n def create(self, username, email, is_premium_member=False, has_support_contract=False):\n user = User(username=username, email=email)\n user.save()\n profile = Profile(\n user=user,\n is_premium_member=is_premium_member,\n has_support_contract=has_support_contract\n )\n profile.save()\n return user\n\n\n\nThis manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our \n.create()\n method on the serializer class can now be re-written to use the new manager method.\n\n\ndef create(self, validated_data):\n return User.objects.create(\n username=validated_data['username'],\n email=validated_data['email']\n is_premium_member=validated_data['profile']['is_premium_member']\n has_support_contract=validated_data['profile']['has_support_contract']\n )\n\n\n\nFor more details on this approach see the Django documentation on \nmodel managers\n, and \nthis blogpost on using model and manager classes\n.\n\n\nDealing with multiple objects\n\n\nThe \nSerializer\n class can also handle serializing or deserializing lists of objects.\n\n\nSerializing multiple objects\n\n\nTo serialize a queryset or list of objects instead of a single object instance, you should pass the \nmany=True\n flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.\n\n\nqueryset = Book.objects.all()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ]\n\n\n\nDeserializing multiple objects\n\n\nThe default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the \nListSerializer\n documentation below.\n\n\nIncluding extra context\n\n\nThere are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.\n\n\nYou can provide arbitrary additional context by passing a \ncontext\n argument when instantiating the serializer. For example:\n\n\nserializer = AccountSerializer(account, context={'request': request})\nserializer.data\n# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}\n\n\n\nThe context dictionary can be used within any serializer field logic, such as a custom \n.to_representation()\n method, by accessing the \nself.context\n attribute.\n\n\n\n\nModelSerializer\n\n\nOften you'll want serializer classes that map closely to Django model definitions.\n\n\nThe \nModelSerializer\n class provides a shortcut that lets you automatically create a \nSerializer\n class with fields that correspond to the Model fields.\n\n\nThe \nModelSerializer\n class is the same as a regular \nSerializer\n class, except that\n:\n\n\n\n\nIt will automatically generate a set of fields for you, based on the model.\n\n\nIt will automatically generate validators for the serializer, such as unique_together validators.\n\n\nIt includes simple default implementations of \n.create()\n and \n.update()\n.\n\n\n\n\nDeclaring a \nModelSerializer\n looks like this:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n\n\n\nBy default, all the model fields on the class will be mapped to a corresponding serializer fields.\n\n\nAny relationships such as foreign keys on the model will be mapped to \nPrimaryKeyRelatedField\n. Reverse relationships are not included by default unless explicitly included as described below.\n\n\nInspecting a \nModelSerializer\n\n\nSerializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with \nModelSerializers\n where you want to determine what set of fields and validators are being automatically created for you.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nSpecifying which fields to include\n\n\nIf you only want a subset of the default fields to be used in a model serializer, you can do so using \nfields\n or \nexclude\n options, just as you would with a \nModelForm\n. It is strongly recommended that you explicitly set all fields that should be serialized using the \nfields\n attribute. This will make it less likely to result in unintentionally exposing data when your models change.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n\n\n\nYou can also set the \nfields\n attribute to the special value \n'__all__'\n to indicate that all fields in the model should be used.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = '__all__'\n\n\n\nYou can set the \nexclude\n attribute to a list of fields to be excluded from the serializer.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n exclude = ('users',)\n\n\n\nIn the example above, if the \nAccount\n model had 3 fields \naccount_name\n, \nusers\n, and \ncreated\n, this will result in the fields \naccount_name\n and \ncreated\n to be serialized.\n\n\nThe names in the \nfields\n and \nexclude\n attributes will normally map to model fields on the model class.\n\n\nAlternatively names in the \nfields\n options can map to properties or methods which take no arguments that exist on the model class.\n\n\nSpecifying nested serialization\n\n\nThe default \nModelSerializer\n uses primary keys for relationships, but you can also easily generate nested representations using the \ndepth\n option:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n depth = 1\n\n\n\nThe \ndepth\n option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.\n\n\nIf you want to customize the way the serialization is done you'll need to define the field yourself.\n\n\nSpecifying fields explicitly\n\n\nYou can add extra fields to a \nModelSerializer\n or override the default fields by declaring fields on the class, just as you would for a \nSerializer\n class.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n groups = serializers.PrimaryKeyRelatedField(many=True)\n\n class Meta:\n model = Account\n\n\n\nExtra fields can correspond to any property or callable on the model.\n\n\nSpecifying read only fields\n\n\nYou may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the \nread_only=True\n attribute, you may use the shortcut Meta option, \nread_only_fields\n.\n\n\nThis option should be a list or tuple of field names, and is declared as follows:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n read_only_fields = ('account_name',)\n\n\n\nModel fields which have \neditable=False\n set, and \nAutoField\n fields will be set to read-only by default, and do not need to be added to the \nread_only_fields\n option.\n\n\n\n\nNote\n: There is a special-case where a read-only field is part of a \nunique_together\n constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.\n\n\nThe right way to deal with this is to specify the field explicitly on the serializer, providing both the \nread_only=True\n and \ndefault=\u2026\n keyword arguments.\n\n\nOne example of this is a read-only relation to the currently authenticated \nUser\n which is \nunique_together\n with another identifier. In this case you would declare the user field like so:\n\n\nuser = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())\n\n\n\nPlease review the \nValidators Documentation\n for details on the \nUniqueTogetherValidator\n and \nCurrentUserDefault\n classes.\n\n\n\n\nAdditional keyword arguments\n\n\nThere is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the \nextra_kwargs\n option. As in the case of \nread_only_fields\n, this means you do not need to explicitly declare the field on the serializer.\n\n\nThis option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:\n\n\nclass CreateUserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('email', 'username', 'password')\n extra_kwargs = {'password': {'write_only': True}}\n\n def create(self, validated_data):\n user = User(\n email=validated_data['email'],\n username=validated_data['username']\n )\n user.set_password(validated_data['password'])\n user.save()\n return user\n\n\n\nRelational fields\n\n\nWhen serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for \nModelSerializer\n is to use the primary keys of the related instances.\n\n\nAlternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.\n\n\nFor full details see the \nserializer relations\n documentation.\n\n\nInheritance of the 'Meta' class\n\n\nThe inner \nMeta\n class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's \nModel\n and \nModelForm\n classes. If you want the \nMeta\n class to inherit from a parent class you must do so explicitly. For example:\n\n\nclass AccountSerializer(MyBaseSerializer):\n class Meta(MyBaseSerializer.Meta):\n model = Account\n\n\n\nTypically we would recommend \nnot\n using inheritance on inner Meta classes, but instead declaring all options explicitly.\n\n\nCustomizing field mappings\n\n\nThe ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.\n\n\nNormally if a \nModelSerializer\n does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular \nSerializer\n class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.\n\n\n.serializer_field_mapping\n\n\nA mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class.\n\n\n.serializer_related_field\n\n\nThis property should be the serializer field class, that is used for relational fields by default.\n\n\nFor \nModelSerializer\n this defaults to \nPrimaryKeyRelatedField\n.\n\n\nFor \nHyperlinkedModelSerializer\n this defaults to \nserializers.HyperlinkedRelatedField\n.\n\n\nserializer_url_field\n\n\nThe serializer field class that should be used for any \nurl\n field on the serializer.\n\n\nDefaults to \nserializers.HyperlinkedIdentityField\n\n\nserializer_choice_field\n\n\nThe serializer field class that should be used for any choice fields on the serializer.\n\n\nDefaults to \nserializers.ChoiceField\n\n\nThe field_class and field_kwargs API\n\n\nThe following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of \n(field_class, field_kwargs)\n.\n\n\n.build_standard_field(self, field_name, model_field)\n\n\nCalled to generate a serializer field that maps to a standard model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_field_mapping\n attribute.\n\n\n.build_relational_field(self, field_name, relation_info)\n\n\nCalled to generate a serializer field that maps to a relational model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_relational_field\n attribute.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_nested_field(self, field_name, relation_info, nested_depth)\n\n\nCalled to generate a serializer field that maps to a relational model field, when the \ndepth\n option has been set.\n\n\nThe default implementation dynamically creates a nested serializer class based on either \nModelSerializer\n or \nHyperlinkedModelSerializer\n.\n\n\nThe \nnested_depth\n will be the value of the \ndepth\n option, minus one.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_property_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field that maps to a property or zero-argument method on the model class.\n\n\nThe default implementation returns a \nReadOnlyField\n class.\n\n\n.build_url_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field for the serializer's own \nurl\n field. The default implementation returns a \nHyperlinkedIdentityField\n class.\n\n\n.build_unknown_field(self, field_name, model_class)\n\n\nCalled when the field name did not map to any model field or model property.\nThe default implementation raises an error, although subclasses may customize this behavior.\n\n\n\n\nHyperlinkedModelSerializer\n\n\nThe \nHyperlinkedModelSerializer\n class is similar to the \nModelSerializer\n class except that it uses hyperlinks to represent relationships, rather than primary keys.\n\n\nBy default the serializer will include a \nurl\n field instead of a primary key field.\n\n\nThe url field will be represented using a \nHyperlinkedIdentityField\n serializer field, and any relationships on the model will be represented using a \nHyperlinkedRelatedField\n serializer field.\n\n\nYou can explicitly include the primary key by adding it to the \nfields\n option, for example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Account\n fields = ('url', 'id', 'account_name', 'users', 'created')\n\n\n\nHow hyperlinked views are determined\n\n\nThere needs to be a way of determining which views should be used for hyperlinking to model instances.\n\n\nBy default hyperlinks are expected to correspond to a view name that matches the style \n'{model_name}-detail'\n, and looks up the instance by a \npk\n keyword argument.\n\n\nYou can override a URL field view name and lookup field by using either, or both of, the \nview_name\n and \nlookup_field\n options in the \nextra_kwargs\n setting, like so:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Account\n fields = ('account_url', 'account_name', 'users', 'created')\n extra_kwargs = {\n 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}\n 'users': {'lookup_field': 'username'}\n }\n\n\n\nAlternatively you can set the fields on the serializer explicitly. For example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='accounts',\n lookup_field='slug'\n )\n users = serializers.HyperlinkedRelatedField(\n view_name='user-detail',\n lookup_field='username',\n many=True,\n read_only=True\n )\n\n class Meta:\n model = Account\n fields = ('url', 'account_name', 'users', 'created')\n\n\n\n\n\nTip\n: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the \nrepr\n of a \nHyperlinkedModelSerializer\n instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.\n\n\n\n\nChanging the URL field name\n\n\nThe name of the URL field defaults to 'url'. You can override this globally, by using the \nURL_FIELD_NAME\n setting.\n\n\n\n\nListSerializer\n\n\nThe \nListSerializer\n class provides the behavior for serializing and validating multiple objects at once. You won't \ntypically\n need to use \nListSerializer\n directly, but should instead simply pass \nmany=True\n when instantiating a serializer.\n\n\nWhen a serializer is instantiated and \nmany=True\n is passed, a \nListSerializer\n instance will be created. The serializer class then becomes a child of the parent \nListSerializer\n\n\nThe following argument can also be passed to a \nListSerializer\n field or a serializer that is passed \nmany=True\n:\n\n\nallow_empty\n\n\nThis is \nTrue\n by default, but can be set to \nFalse\n if you want to disallow empty lists as valid input.\n\n\nCustomizing \nListSerializer\n behavior\n\n\nThere \nare\n a few use cases when you might want to customize the \nListSerializer\n behavior. For example:\n\n\n\n\nYou want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list.\n\n\nYou want to customize the create or update behavior of multiple objects.\n\n\n\n\nFor these cases you can modify the class that is used when \nmany=True\n is passed, by using the \nlist_serializer_class\n option on the serializer \nMeta\n class.\n\n\nFor example:\n\n\nclass CustomListSerializer(serializers.ListSerializer):\n ...\n\nclass CustomSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = CustomListSerializer\n\n\n\nCustomizing multiple create\n\n\nThe default implementation for multiple object creation is to simply call \n.create()\n for each item in the list. If you want to customize this behavior, you'll need to customize the \n.create()\n method on \nListSerializer\n class that is used when \nmany=True\n is passed.\n\n\nFor example:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n def create(self, validated_data):\n books = [Book(**item) for item in validated_data]\n return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = BookListSerializer\n\n\n\nCustomizing multiple update\n\n\nBy default the \nListSerializer\n class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.\n\n\nTo support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:\n\n\n\n\nHow do you determine which instance should be updated for each item in the list of data?\n\n\nHow should insertions be handled? Are they invalid, or do they create new objects?\n\n\nHow should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?\n\n\nHow should ordering be handled? Does changing the position of two items imply any state change or is it ignored?\n\n\n\n\nYou will need to add an explicit \nid\n field to the instance serializer. The default implicitly-generated \nid\n field is marked as \nread_only\n. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's \nupdate\n method.\n\n\nHere's an example of how you might choose to implement multiple updates:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n def update(self, instance, validated_data):\n # Maps for id-\ninstance and id-\ndata item.\n book_mapping = {book.id: book for book in instance}\n data_mapping = {item['id']: item for item in validated_data}\n\n # Perform creations and updates.\n ret = []\n for book_id, data in data_mapping.items():\n book = book_mapping.get(book_id, None)\n if book is None:\n ret.append(self.child.create(data))\n else:\n ret.append(self.child.update(book, data))\n\n # Perform deletions.\n for book_id, book in book_mapping.items():\n if book_id not in data_mapping:\n book.delete()\n\n return ret\n\nclass BookSerializer(serializers.Serializer):\n # We need to identify elements in the list using their primary key,\n # so use a writable field here, rather than the default which would be read-only.\n id = serializers.IntegerField()\n\n ...\n id = serializers.IntegerField(required=False)\n\n class Meta:\n list_serializer_class = BookListSerializer\n\n\n\nIt is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the \nallow_add_remove\n behavior that was present in REST framework 2.\n\n\nCustomizing ListSerializer initialization\n\n\nWhen a serializer with \nmany=True\n is instantiated, we need to determine which arguments and keyword arguments should be passed to the \n.__init__()\n method for both the child \nSerializer\n class, and for the parent \nListSerializer\n class.\n\n\nThe default implementation is to pass all arguments to both classes, except for \nvalidators\n, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.\n\n\nOccasionally you might need to explicitly specify how the child and parent classes should be instantiated when \nmany=True\n is passed. You can do so by using the \nmany_init\n class method.\n\n\n @classmethod\n def many_init(cls, *args, **kwargs):\n # Instantiate the child serializer.\n kwargs['child'] = cls()\n # Instantiate the parent list serializer.\n return CustomListSerializer(*args, **kwargs)\n\n\n\n\n\nBaseSerializer\n\n\nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns any errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) \n 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n\n\n\nCreating new base classes\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n\n\n\n\n\nAdvanced serializer usage\n\n\nOverriding serialization and deserialization behavior\n\n\nIf you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the \n.to_representation()\n or \n.to_internal_value()\n methods.\n\n\nSome reasons this might be useful include...\n\n\n\n\nAdding new behavior for new serializer base classes.\n\n\nModifying the behavior slightly for an existing class.\n\n\nImproving serialization performance for a frequently accessed API endpoint that returns lots of data.\n\n\n\n\nThe signatures for these methods are as follows:\n\n\n.to_representation(self, obj)\n\n\nTakes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.\n\n\n.to_internal_value(self, data)\n\n\nTakes the unvalidated incoming data as input and should return the validated data that will be made available as \nserializer.validated_data\n. The return value will also be passed to the \n.create()\n or \n.update()\n methods if \n.save()\n is called on the serializer class.\n\n\nIf any of the validation fails, then the method should raise a \nserializers.ValidationError(errors)\n. Typically the \nerrors\n argument here will be a dictionary mapping field names to error messages.\n\n\nThe \ndata\n argument passed to this method will normally be the value of \nrequest.data\n, so the datatype it provides will depend on the parser classes you have configured for your API.\n\n\nDynamically modifying fields\n\n\nOnce a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the \n.fields\n attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.\n\n\nModifying the \nfields\n argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.\n\n\nExample\n\n\nFor example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:\n\n\nclass DynamicFieldsModelSerializer(serializers.ModelSerializer):\n \"\"\"\n A ModelSerializer that takes an additional `fields` argument that\n controls which fields should be displayed.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Don't pass the 'fields' arg up to the superclass\n fields = kwargs.pop('fields', None)\n\n # Instantiate the superclass normally\n super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)\n\n if fields is not None:\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(fields)\n existing = set(self.fields.keys())\n for field_name in existing - allowed:\n self.fields.pop(field_name)\n\n\n\nThis would then allow you to do the following:\n\n\n class UserSerializer(DynamicFieldsModelSerializer):\n\n class Meta:\n\n model = User\n\n fields = ('id', 'username', 'email')\n\n\n\n print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\n\n\n\n print UserSerializer(user, fields=('id', 'email'))\n{'id': 2, 'email': 'jon@example.com'}\n\n\n\nCustomizing the default fields\n\n\nREST framework 2 provided an API to allow developers to override how a \nModelSerializer\n class would automatically generate the default set of fields.\n\n\nThis API included the \n.get_field()\n, \n.get_pk_field()\n and other methods.\n\n\nBecause the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.\n\n\nA new interface for controlling this behavior is currently planned for REST framework 3.1.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango REST marshmallow\n\n\nThe \ndjango-rest-marshmallow\n package provides an alternative implementation for serializers, using the python \nmarshmallow\n library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.\n\n\nSerpy\n\n\nThe \nserpy\n package is an alternative implementation for serializers that is built for speed. \nSerpy\n serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.\n\n\nMongoengineModelSerializer\n\n\nThe \ndjango-rest-framework-mongoengine\n package provides a \nMongoEngineModelSerializer\n serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\nGeoFeatureModelSerializer\n\n\nThe \ndjango-rest-framework-gis\n package provides a \nGeoFeatureModelSerializer\n serializer class that supports GeoJSON both for read and write operations.\n\n\nHStoreSerializer\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreSerializer\n to support \ndjango-hstore\n \nDictionaryField\n model field and its \nschema-mode\n feature.\n\n\nDynamic REST\n\n\nThe \ndynamic-rest\n package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.\n\n\nHTML JSON Forms\n\n\nThe \nhtml-json-forms\n package provides an algorithm and serializer for processing \nform\n submissions per the (inactive) \nHTML JSON Form specification\n. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, \ninput name=\"items[0][id]\" value=\"5\"\n will be interpreted as \n{\"items\": [{\"id\": \"5\"}]}\n.",
+ "text": "Serializers\n\n\n\n\nExpanding the usefulness of the serializers is something that we would\nlike to address. However, it's not a trivial problem, and it\nwill take some serious design work.\n\n\n Russell Keith-Magee, \nDjango users group\n\n\n\n\nSerializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into \nJSON\n, \nXML\n or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.\n\n\nThe serializers in REST framework work very similarly to Django's \nForm\n and \nModelForm\n classes. We provide a \nSerializer\n class which gives you a powerful, generic way to control the output of your responses, as well as a \nModelSerializer\n class which provides a useful shortcut for creating serializers that deal with model instances and querysets.\n\n\nDeclaring Serializers\n\n\nLet's start by creating a simple object we can use for example purposes:\n\n\nfrom datetime import datetime\n\nclass Comment(object):\n def __init__(self, email, content, created=None):\n self.email = email\n self.content = content\n self.created = created or datetime.now()\n\ncomment = Comment(email='leila@example.com', content='foo bar')\n\n\n\nWe'll declare a serializer that we can use to serialize and deserialize data that corresponds to \nComment\n objects.\n\n\nDeclaring a serializer looks very similar to declaring a form:\n\n\nfrom rest_framework import serializers\n\nclass CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nSerializing objects\n\n\nWe can now use \nCommentSerializer\n to serialize a comment, or list of comments. Again, using the \nSerializer\n class looks a lot like using a \nForm\n class.\n\n\nserializer = CommentSerializer(comment)\nserializer.data\n# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into \njson\n.\n\n\nfrom rest_framework.renderers import JSONRenderer\n\njson = JSONRenderer().render(serializer.data)\njson\n# b'{\"email\":\"leila@example.com\",\"content\":\"foo bar\",\"created\":\"2016-01-27T15:17:10.375877\"}'\n\n\n\nDeserializing objects\n\n\nDeserialization is similar. First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\nfrom rest_framework.parsers import JSONParser\n\nstream = BytesIO(json)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a dictionary of validated data.\n\n\nserializer = CommentSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}\n\n\n\nSaving instances\n\n\nIf we want to be able to return complete object instances based on the validated data we need to implement one or both of the \n.create()\n and \nupdate()\n methods. For example:\n\n\nclass CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n def create(self, validated_data):\n return Comment(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n return instance\n\n\n\nIf your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if \nComment\n was a Django model, the methods might look like this:\n\n\n def create(self, validated_data):\n return Comment.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n instance.save()\n return instance\n\n\n\nNow when deserializing data, we can call \n.save()\n to return an object instance, based on the validated data.\n\n\ncomment = serializer.save()\n\n\n\nCalling \n.save()\n will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:\n\n\n# .save() will create a new instance.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data)\n\n\n\nBoth the \n.create()\n and \n.update()\n methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.\n\n\nPassing additional attributes to \n.save()\n\n\nSometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.\n\n\nYou can do so by including additional keyword arguments when calling \n.save()\n. For example:\n\n\nserializer.save(owner=request.user)\n\n\n\nAny additional keyword arguments will be included in the \nvalidated_data\n argument when \n.create()\n or \n.update()\n are called.\n\n\nOverriding \n.save()\n directly.\n\n\nIn some cases the \n.create()\n and \n.update()\n method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.\n\n\nIn these cases you might instead choose to override \n.save()\n directly, as being more readable and meaningful.\n\n\nFor example:\n\n\nclass ContactForm(serializers.Serializer):\n email = serializers.EmailField()\n message = serializers.CharField()\n\n def save(self):\n email = self.validated_data['email']\n message = self.validated_data['message']\n send_email(from=email, message=message)\n\n\n\nNote that in the case above we're now having to access the serializer \n.validated_data\n property directly.\n\n\nValidation\n\n\nWhen deserializing data, you always need to call \nis_valid()\n before attempting to access the validated data, or save an object instance. If any validation errors occur, the \n.errors\n property will contain a dictionary representing the resulting error messages. For example:\n\n\nserializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}\n\n\n\nEach key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The \nnon_field_errors\n key may also be present, and will list any general validation errors. The name of the \nnon_field_errors\n key may be customized using the \nNON_FIELD_ERRORS_KEY\n REST framework setting.\n\n\nWhen deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.\n\n\nRaising an exception on invalid data\n\n\nThe \n.is_valid()\n method takes an optional \nraise_exception\n flag that will cause it to raise a \nserializers.ValidationError\n exception if there are validation errors.\n\n\nThese exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return \nHTTP 400 Bad Request\n responses by default.\n\n\n# Return a 400 response if the data was invalid.\nserializer.is_valid(raise_exception=True)\n\n\n\nField-level validation\n\n\nYou can specify custom field-level validation by adding \n.validate_\nfield_name\n methods to your \nSerializer\n subclass. These are similar to the \n.clean_\nfield_name\n methods on Django forms.\n\n\nThese methods take a single argument, which is the field value that requires validation.\n\n\nYour \nvalidate_\nfield_name\n methods should return the validated value or raise a \nserializers.ValidationError\n. For example:\n\n\nfrom rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n title = serializers.CharField(max_length=100)\n content = serializers.CharField()\n\n def validate_title(self, value):\n \"\"\"\n Check that the blog post is about Django.\n \"\"\"\n if 'django' not in value.lower():\n raise serializers.ValidationError(\"Blog post is not about Django\")\n return value\n\n\n\n\n\nNote:\n If your \nfield_name\n is declared on your serializer with the parameter \nrequired=False\n then this validation step will not take place if the field is not included.\n\n\n\n\nObject-level validation\n\n\nTo do any other validation that requires access to multiple fields, add a method called \n.validate()\n to your \nSerializer\n subclass. This method takes a single argument, which is a dictionary of field values. It should raise a \nValidationError\n if necessary, or just return the validated values. For example:\n\n\nfrom rest_framework import serializers\n\nclass EventSerializer(serializers.Serializer):\n description = serializers.CharField(max_length=100)\n start = serializers.DateTimeField()\n finish = serializers.DateTimeField()\n\n def validate(self, data):\n \"\"\"\n Check that the start is before the stop.\n \"\"\"\n if data['start'] \n data['finish']:\n raise serializers.ValidationError(\"finish must occur after start\")\n return data\n\n\n\nValidators\n\n\nIndividual fields on a serializer can include validators, by declaring them on the field instance, for example:\n\n\ndef multiple_of_ten(value):\n if value % 10 != 0:\n raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n score = IntegerField(validators=[multiple_of_ten])\n ...\n\n\n\nSerializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner \nMeta\n class, like so:\n\n\nclass EventSerializer(serializers.Serializer):\n name = serializers.CharField()\n room_number = serializers.IntegerField(choices=[101, 102, 103, 201])\n date = serializers.DateField()\n\n class Meta:\n # Each room only has one event per day.\n validators = UniqueTogetherValidator(\n queryset=Event.objects.all(),\n fields=['room_number', 'date']\n )\n\n\n\nFor more information see the \nvalidators documentation\n.\n\n\nAccessing the initial data and instance\n\n\nWhen passing an initial object or queryset to a serializer instance, the object will be made available as \n.instance\n. If no initial object is passed then the \n.instance\n attribute will be \nNone\n.\n\n\nWhen passing data to a serializer instance, the unmodified data will be made available as \n.initial_data\n. If the data keyword argument is not passed then the \n.initial_data\n attribute will not exist.\n\n\nPartial updates\n\n\nBy default, serializers must be passed values for all required fields or they will raise validation errors. You can use the \npartial\n argument in order to allow partial updates.\n\n\n# Update `comment` with partial data\nserializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)\n\n\n\nDealing with nested objects\n\n\nThe previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.\n\n\nThe \nSerializer\n class is itself a type of \nField\n, and can be used to represent relationships where one object type is nested inside another.\n\n\nclass UserSerializer(serializers.Serializer):\n email = serializers.EmailField()\n username = serializers.CharField(max_length=100)\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nIf a nested representation may optionally accept the \nNone\n value you should pass the \nrequired=False\n flag to the nested serializer.\n\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer(required=False) # May be an anonymous user.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nSimilarly if a nested representation should be a list of items, you should pass the \nmany=True\n flag to the nested serialized.\n\n\nclass CommentSerializer(serializers.Serializer):\n user = UserSerializer(required=False)\n edits = EditItemSerializer(many=True) # A nested list of 'edit' items.\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n\n\nWritable nested representations\n\n\nWhen dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object.\n\n\nserializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}\n\n\n\nSimilarly, the \n.validated_data\n property will include nested data structures.\n\n\nWriting \n.create()\n methods for nested representations\n\n\nIf you're supporting writable nested representations you'll need to write \n.create()\n or \n.update()\n methods that handle saving multiple objects.\n\n\nThe following example demonstrates how you might handle creating a user with a nested profile object.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n\n\n\nWriting \n.update()\n methods for nested representations\n\n\nFor updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is \nNone\n, or not provided, which of the following should occur?\n\n\n\n\nSet the relationship to \nNULL\n in the database.\n\n\nDelete the associated instance.\n\n\nIgnore the data and leave the instance as it is.\n\n\nRaise a validation error.\n\n\n\n\nHere's an example for an \nupdate()\n method on our previous \nUserSerializer\n class.\n\n\n def update(self, instance, validated_data):\n profile_data = validated_data.pop('profile')\n # Unless the application properly enforces that this field is\n # always set, the follow could raise a `DoesNotExist`, which\n # would need to be handled.\n profile = instance.profile\n\n instance.username = validated_data.get('username', instance.username)\n instance.email = validated_data.get('email', instance.email)\n instance.save()\n\n profile.is_premium_member = profile_data.get(\n 'is_premium_member',\n profile.is_premium_member\n )\n profile.has_support_contract = profile_data.get(\n 'has_support_contract',\n profile.has_support_contract\n )\n profile.save()\n\n return instance\n\n\n\nBecause the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default \nModelSerializer\n \n.create()\n and \n.update()\n methods do not include support for writable nested representations.\n\n\nIt is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.\n\n\nHandling saving related instances in model manager classes\n\n\nAn alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.\n\n\nFor example, suppose we wanted to ensure that \nUser\n instances and \nProfile\n instances are always created together as a pair. We might write a custom manager class that looks something like this:\n\n\nclass UserManager(models.Manager):\n ...\n\n def create(self, username, email, is_premium_member=False, has_support_contract=False):\n user = User(username=username, email=email)\n user.save()\n profile = Profile(\n user=user,\n is_premium_member=is_premium_member,\n has_support_contract=has_support_contract\n )\n profile.save()\n return user\n\n\n\nThis manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our \n.create()\n method on the serializer class can now be re-written to use the new manager method.\n\n\ndef create(self, validated_data):\n return User.objects.create(\n username=validated_data['username'],\n email=validated_data['email']\n is_premium_member=validated_data['profile']['is_premium_member']\n has_support_contract=validated_data['profile']['has_support_contract']\n )\n\n\n\nFor more details on this approach see the Django documentation on \nmodel managers\n, and \nthis blogpost on using model and manager classes\n.\n\n\nDealing with multiple objects\n\n\nThe \nSerializer\n class can also handle serializing or deserializing lists of objects.\n\n\nSerializing multiple objects\n\n\nTo serialize a queryset or list of objects instead of a single object instance, you should pass the \nmany=True\n flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.\n\n\nqueryset = Book.objects.all()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ]\n\n\n\nDeserializing multiple objects\n\n\nThe default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the \nListSerializer\n documentation below.\n\n\nIncluding extra context\n\n\nThere are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.\n\n\nYou can provide arbitrary additional context by passing a \ncontext\n argument when instantiating the serializer. For example:\n\n\nserializer = AccountSerializer(account, context={'request': request})\nserializer.data\n# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}\n\n\n\nThe context dictionary can be used within any serializer field logic, such as a custom \n.to_representation()\n method, by accessing the \nself.context\n attribute.\n\n\n\n\nModelSerializer\n\n\nOften you'll want serializer classes that map closely to Django model definitions.\n\n\nThe \nModelSerializer\n class provides a shortcut that lets you automatically create a \nSerializer\n class with fields that correspond to the Model fields.\n\n\nThe \nModelSerializer\n class is the same as a regular \nSerializer\n class, except that\n:\n\n\n\n\nIt will automatically generate a set of fields for you, based on the model.\n\n\nIt will automatically generate validators for the serializer, such as unique_together validators.\n\n\nIt includes simple default implementations of \n.create()\n and \n.update()\n.\n\n\n\n\nDeclaring a \nModelSerializer\n looks like this:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n\n\n\nBy default, all the model fields on the class will be mapped to a corresponding serializer fields.\n\n\nAny relationships such as foreign keys on the model will be mapped to \nPrimaryKeyRelatedField\n. Reverse relationships are not included by default unless explicitly included as described below.\n\n\nInspecting a \nModelSerializer\n\n\nSerializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with \nModelSerializers\n where you want to determine what set of fields and validators are being automatically created for you.\n\n\nTo do so, open the Django shell, using \npython manage.py shell\n, then import the serializer class, instantiate it, and print the object representation\u2026\n\n\n from myapp.serializers import AccountSerializer\n\n serializer = AccountSerializer()\n\n print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nSpecifying which fields to include\n\n\nIf you only want a subset of the default fields to be used in a model serializer, you can do so using \nfields\n or \nexclude\n options, just as you would with a \nModelForm\n. It is strongly recommended that you explicitly set all fields that should be serialized using the \nfields\n attribute. This will make it less likely to result in unintentionally exposing data when your models change.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n\n\n\nYou can also set the \nfields\n attribute to the special value \n'__all__'\n to indicate that all fields in the model should be used.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = '__all__'\n\n\n\nYou can set the \nexclude\n attribute to a list of fields to be excluded from the serializer.\n\n\nFor example:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n exclude = ('users',)\n\n\n\nIn the example above, if the \nAccount\n model had 3 fields \naccount_name\n, \nusers\n, and \ncreated\n, this will result in the fields \naccount_name\n and \ncreated\n to be serialized.\n\n\nThe names in the \nfields\n and \nexclude\n attributes will normally map to model fields on the model class.\n\n\nAlternatively names in the \nfields\n options can map to properties or methods which take no arguments that exist on the model class.\n\n\nSpecifying nested serialization\n\n\nThe default \nModelSerializer\n uses primary keys for relationships, but you can also easily generate nested representations using the \ndepth\n option:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n depth = 1\n\n\n\nThe \ndepth\n option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.\n\n\nIf you want to customize the way the serialization is done you'll need to define the field yourself.\n\n\nSpecifying fields explicitly\n\n\nYou can add extra fields to a \nModelSerializer\n or override the default fields by declaring fields on the class, just as you would for a \nSerializer\n class.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n url = serializers.CharField(source='get_absolute_url', read_only=True)\n groups = serializers.PrimaryKeyRelatedField(many=True)\n\n class Meta:\n model = Account\n\n\n\nExtra fields can correspond to any property or callable on the model.\n\n\nSpecifying read only fields\n\n\nYou may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the \nread_only=True\n attribute, you may use the shortcut Meta option, \nread_only_fields\n.\n\n\nThis option should be a list or tuple of field names, and is declared as follows:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created')\n read_only_fields = ('account_name',)\n\n\n\nModel fields which have \neditable=False\n set, and \nAutoField\n fields will be set to read-only by default, and do not need to be added to the \nread_only_fields\n option.\n\n\n\n\nNote\n: There is a special-case where a read-only field is part of a \nunique_together\n constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.\n\n\nThe right way to deal with this is to specify the field explicitly on the serializer, providing both the \nread_only=True\n and \ndefault=\u2026\n keyword arguments.\n\n\nOne example of this is a read-only relation to the currently authenticated \nUser\n which is \nunique_together\n with another identifier. In this case you would declare the user field like so:\n\n\nuser = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())\n\n\n\nPlease review the \nValidators Documentation\n for details on the \nUniqueTogetherValidator\n and \nCurrentUserDefault\n classes.\n\n\n\n\nAdditional keyword arguments\n\n\nThere is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the \nextra_kwargs\n option. As in the case of \nread_only_fields\n, this means you do not need to explicitly declare the field on the serializer.\n\n\nThis option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:\n\n\nclass CreateUserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('email', 'username', 'password')\n extra_kwargs = {'password': {'write_only': True}}\n\n def create(self, validated_data):\n user = User(\n email=validated_data['email'],\n username=validated_data['username']\n )\n user.set_password(validated_data['password'])\n user.save()\n return user\n\n\n\nRelational fields\n\n\nWhen serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for \nModelSerializer\n is to use the primary keys of the related instances.\n\n\nAlternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.\n\n\nFor full details see the \nserializer relations\n documentation.\n\n\nInheritance of the 'Meta' class\n\n\nThe inner \nMeta\n class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's \nModel\n and \nModelForm\n classes. If you want the \nMeta\n class to inherit from a parent class you must do so explicitly. For example:\n\n\nclass AccountSerializer(MyBaseSerializer):\n class Meta(MyBaseSerializer.Meta):\n model = Account\n\n\n\nTypically we would recommend \nnot\n using inheritance on inner Meta classes, but instead declaring all options explicitly.\n\n\nCustomizing field mappings\n\n\nThe ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.\n\n\nNormally if a \nModelSerializer\n does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular \nSerializer\n class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.\n\n\n.serializer_field_mapping\n\n\nA mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class.\n\n\n.serializer_related_field\n\n\nThis property should be the serializer field class, that is used for relational fields by default.\n\n\nFor \nModelSerializer\n this defaults to \nPrimaryKeyRelatedField\n.\n\n\nFor \nHyperlinkedModelSerializer\n this defaults to \nserializers.HyperlinkedRelatedField\n.\n\n\nserializer_url_field\n\n\nThe serializer field class that should be used for any \nurl\n field on the serializer.\n\n\nDefaults to \nserializers.HyperlinkedIdentityField\n\n\nserializer_choice_field\n\n\nThe serializer field class that should be used for any choice fields on the serializer.\n\n\nDefaults to \nserializers.ChoiceField\n\n\nThe field_class and field_kwargs API\n\n\nThe following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of \n(field_class, field_kwargs)\n.\n\n\n.build_standard_field(self, field_name, model_field)\n\n\nCalled to generate a serializer field that maps to a standard model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_field_mapping\n attribute.\n\n\n.build_relational_field(self, field_name, relation_info)\n\n\nCalled to generate a serializer field that maps to a relational model field.\n\n\nThe default implementation returns a serializer class based on the \nserializer_relational_field\n attribute.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_nested_field(self, field_name, relation_info, nested_depth)\n\n\nCalled to generate a serializer field that maps to a relational model field, when the \ndepth\n option has been set.\n\n\nThe default implementation dynamically creates a nested serializer class based on either \nModelSerializer\n or \nHyperlinkedModelSerializer\n.\n\n\nThe \nnested_depth\n will be the value of the \ndepth\n option, minus one.\n\n\nThe \nrelation_info\n argument is a named tuple, that contains \nmodel_field\n, \nrelated_model\n, \nto_many\n and \nhas_through_model\n properties.\n\n\n.build_property_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field that maps to a property or zero-argument method on the model class.\n\n\nThe default implementation returns a \nReadOnlyField\n class.\n\n\n.build_url_field(self, field_name, model_class)\n\n\nCalled to generate a serializer field for the serializer's own \nurl\n field. The default implementation returns a \nHyperlinkedIdentityField\n class.\n\n\n.build_unknown_field(self, field_name, model_class)\n\n\nCalled when the field name did not map to any model field or model property.\nThe default implementation raises an error, although subclasses may customize this behavior.\n\n\n\n\nHyperlinkedModelSerializer\n\n\nThe \nHyperlinkedModelSerializer\n class is similar to the \nModelSerializer\n class except that it uses hyperlinks to represent relationships, rather than primary keys.\n\n\nBy default the serializer will include a \nurl\n field instead of a primary key field.\n\n\nThe url field will be represented using a \nHyperlinkedIdentityField\n serializer field, and any relationships on the model will be represented using a \nHyperlinkedRelatedField\n serializer field.\n\n\nYou can explicitly include the primary key by adding it to the \nfields\n option, for example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Account\n fields = ('url', 'id', 'account_name', 'users', 'created')\n\n\n\nAbsolute and relative URLs\n\n\nWhen instantiating a \nHyperlinkedModelSerializer\n you must include the current\n\nrequest\n in the serializer context, for example:\n\n\nserializer = AccountSerializer(queryset, context={'request': request})\n\n\n\nDoing so will ensure that the hyperlinks can include an appropriate hostname,\nso that the resulting representation uses fully qualified URLs, such as:\n\n\nhttp://api.example.com/accounts/1/\n\n\n\nRather than relative URLs, such as:\n\n\n/accounts/1/\n\n\n\nIf you \ndo\n want to use relative URLs, you should explicitly pass \n{'request': None}\n\nin the serializer context.\n\n\nHow hyperlinked views are determined\n\n\nThere needs to be a way of determining which views should be used for hyperlinking to model instances.\n\n\nBy default hyperlinks are expected to correspond to a view name that matches the style \n'{model_name}-detail'\n, and looks up the instance by a \npk\n keyword argument.\n\n\nYou can override a URL field view name and lookup field by using either, or both of, the \nview_name\n and \nlookup_field\n options in the \nextra_kwargs\n setting, like so:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Account\n fields = ('account_url', 'account_name', 'users', 'created')\n extra_kwargs = {\n 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}\n 'users': {'lookup_field': 'username'}\n }\n\n\n\nAlternatively you can set the fields on the serializer explicitly. For example:\n\n\nclass AccountSerializer(serializers.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='accounts',\n lookup_field='slug'\n )\n users = serializers.HyperlinkedRelatedField(\n view_name='user-detail',\n lookup_field='username',\n many=True,\n read_only=True\n )\n\n class Meta:\n model = Account\n fields = ('url', 'account_name', 'users', 'created')\n\n\n\n\n\nTip\n: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the \nrepr\n of a \nHyperlinkedModelSerializer\n instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.\n\n\n\n\nChanging the URL field name\n\n\nThe name of the URL field defaults to 'url'. You can override this globally, by using the \nURL_FIELD_NAME\n setting.\n\n\n\n\nListSerializer\n\n\nThe \nListSerializer\n class provides the behavior for serializing and validating multiple objects at once. You won't \ntypically\n need to use \nListSerializer\n directly, but should instead simply pass \nmany=True\n when instantiating a serializer.\n\n\nWhen a serializer is instantiated and \nmany=True\n is passed, a \nListSerializer\n instance will be created. The serializer class then becomes a child of the parent \nListSerializer\n\n\nThe following argument can also be passed to a \nListSerializer\n field or a serializer that is passed \nmany=True\n:\n\n\nallow_empty\n\n\nThis is \nTrue\n by default, but can be set to \nFalse\n if you want to disallow empty lists as valid input.\n\n\nCustomizing \nListSerializer\n behavior\n\n\nThere \nare\n a few use cases when you might want to customize the \nListSerializer\n behavior. For example:\n\n\n\n\nYou want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list.\n\n\nYou want to customize the create or update behavior of multiple objects.\n\n\n\n\nFor these cases you can modify the class that is used when \nmany=True\n is passed, by using the \nlist_serializer_class\n option on the serializer \nMeta\n class.\n\n\nFor example:\n\n\nclass CustomListSerializer(serializers.ListSerializer):\n ...\n\nclass CustomSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = CustomListSerializer\n\n\n\nCustomizing multiple create\n\n\nThe default implementation for multiple object creation is to simply call \n.create()\n for each item in the list. If you want to customize this behavior, you'll need to customize the \n.create()\n method on \nListSerializer\n class that is used when \nmany=True\n is passed.\n\n\nFor example:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n def create(self, validated_data):\n books = [Book(**item) for item in validated_data]\n return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = BookListSerializer\n\n\n\nCustomizing multiple update\n\n\nBy default the \nListSerializer\n class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.\n\n\nTo support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:\n\n\n\n\nHow do you determine which instance should be updated for each item in the list of data?\n\n\nHow should insertions be handled? Are they invalid, or do they create new objects?\n\n\nHow should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?\n\n\nHow should ordering be handled? Does changing the position of two items imply any state change or is it ignored?\n\n\n\n\nYou will need to add an explicit \nid\n field to the instance serializer. The default implicitly-generated \nid\n field is marked as \nread_only\n. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's \nupdate\n method.\n\n\nHere's an example of how you might choose to implement multiple updates:\n\n\nclass BookListSerializer(serializers.ListSerializer):\n def update(self, instance, validated_data):\n # Maps for id-\ninstance and id-\ndata item.\n book_mapping = {book.id: book for book in instance}\n data_mapping = {item['id']: item for item in validated_data}\n\n # Perform creations and updates.\n ret = []\n for book_id, data in data_mapping.items():\n book = book_mapping.get(book_id, None)\n if book is None:\n ret.append(self.child.create(data))\n else:\n ret.append(self.child.update(book, data))\n\n # Perform deletions.\n for book_id, book in book_mapping.items():\n if book_id not in data_mapping:\n book.delete()\n\n return ret\n\nclass BookSerializer(serializers.Serializer):\n # We need to identify elements in the list using their primary key,\n # so use a writable field here, rather than the default which would be read-only.\n id = serializers.IntegerField()\n\n ...\n id = serializers.IntegerField(required=False)\n\n class Meta:\n list_serializer_class = BookListSerializer\n\n\n\nIt is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the \nallow_add_remove\n behavior that was present in REST framework 2.\n\n\nCustomizing ListSerializer initialization\n\n\nWhen a serializer with \nmany=True\n is instantiated, we need to determine which arguments and keyword arguments should be passed to the \n.__init__()\n method for both the child \nSerializer\n class, and for the parent \nListSerializer\n class.\n\n\nThe default implementation is to pass all arguments to both classes, except for \nvalidators\n, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.\n\n\nOccasionally you might need to explicitly specify how the child and parent classes should be instantiated when \nmany=True\n is passed. You can do so by using the \nmany_init\n class method.\n\n\n @classmethod\n def many_init(cls, *args, **kwargs):\n # Instantiate the child serializer.\n kwargs['child'] = cls()\n # Instantiate the parent list serializer.\n return CustomListSerializer(*args, **kwargs)\n\n\n\n\n\nBaseSerializer\n\n\nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns any errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) \n 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n\n\n\nCreating new base classes\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n\n\n\n\n\nAdvanced serializer usage\n\n\nOverriding serialization and deserialization behavior\n\n\nIf you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the \n.to_representation()\n or \n.to_internal_value()\n methods.\n\n\nSome reasons this might be useful include...\n\n\n\n\nAdding new behavior for new serializer base classes.\n\n\nModifying the behavior slightly for an existing class.\n\n\nImproving serialization performance for a frequently accessed API endpoint that returns lots of data.\n\n\n\n\nThe signatures for these methods are as follows:\n\n\n.to_representation(self, obj)\n\n\nTakes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.\n\n\n.to_internal_value(self, data)\n\n\nTakes the unvalidated incoming data as input and should return the validated data that will be made available as \nserializer.validated_data\n. The return value will also be passed to the \n.create()\n or \n.update()\n methods if \n.save()\n is called on the serializer class.\n\n\nIf any of the validation fails, then the method should raise a \nserializers.ValidationError(errors)\n. Typically the \nerrors\n argument here will be a dictionary mapping field names to error messages.\n\n\nThe \ndata\n argument passed to this method will normally be the value of \nrequest.data\n, so the datatype it provides will depend on the parser classes you have configured for your API.\n\n\nDynamically modifying fields\n\n\nOnce a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the \n.fields\n attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.\n\n\nModifying the \nfields\n argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.\n\n\nExample\n\n\nFor example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:\n\n\nclass DynamicFieldsModelSerializer(serializers.ModelSerializer):\n \"\"\"\n A ModelSerializer that takes an additional `fields` argument that\n controls which fields should be displayed.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Don't pass the 'fields' arg up to the superclass\n fields = kwargs.pop('fields', None)\n\n # Instantiate the superclass normally\n super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)\n\n if fields is not None:\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(fields)\n existing = set(self.fields.keys())\n for field_name in existing - allowed:\n self.fields.pop(field_name)\n\n\n\nThis would then allow you to do the following:\n\n\n class UserSerializer(DynamicFieldsModelSerializer):\n\n class Meta:\n\n model = User\n\n fields = ('id', 'username', 'email')\n\n\n\n print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}\n\n\n\n print UserSerializer(user, fields=('id', 'email'))\n{'id': 2, 'email': 'jon@example.com'}\n\n\n\nCustomizing the default fields\n\n\nREST framework 2 provided an API to allow developers to override how a \nModelSerializer\n class would automatically generate the default set of fields.\n\n\nThis API included the \n.get_field()\n, \n.get_pk_field()\n and other methods.\n\n\nBecause the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.\n\n\nA new interface for controlling this behavior is currently planned for REST framework 3.1.\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango REST marshmallow\n\n\nThe \ndjango-rest-marshmallow\n package provides an alternative implementation for serializers, using the python \nmarshmallow\n library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.\n\n\nSerpy\n\n\nThe \nserpy\n package is an alternative implementation for serializers that is built for speed. \nSerpy\n serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.\n\n\nMongoengineModelSerializer\n\n\nThe \ndjango-rest-framework-mongoengine\n package provides a \nMongoEngineModelSerializer\n serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\nGeoFeatureModelSerializer\n\n\nThe \ndjango-rest-framework-gis\n package provides a \nGeoFeatureModelSerializer\n serializer class that supports GeoJSON both for read and write operations.\n\n\nHStoreSerializer\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreSerializer\n to support \ndjango-hstore\n \nDictionaryField\n model field and its \nschema-mode\n feature.\n\n\nDynamic REST\n\n\nThe \ndynamic-rest\n package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.\n\n\nHTML JSON Forms\n\n\nThe \nhtml-json-forms\n package provides an algorithm and serializer for processing \nform\n submissions per the (inactive) \nHTML JSON Form specification\n. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, \ninput name=\"items[0][id]\" value=\"5\"\n will be interpreted as \n{\"items\": [{\"id\": \"5\"}]}\n.",
"title": "Serializers"
},
{
@@ -1102,14 +1327,44 @@
},
{
"location": "/api-guide/serializers/#saving-instances",
- "text": "If we want to be able to return complete object instances based on the validated data we need to implement one or both of the .create() and update() methods. For example: class CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n def create(self, validated_data):\n return Comment(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n return instance If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this: def create(self, validated_data):\n return Comment.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n instance.save()\n return instance Now when deserializing data, we can call .save() to return an object instance, based on the validated data. comment = serializer.save() Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: # .save() will create a new instance.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data) Both the .create() and .update() methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class. Passing additional attributes to .save() Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data. You can do so by including additional keyword arguments when calling .save() . For example: serializer.save(owner=request.user) Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called. Overriding .save() directly. In some cases the .create() and .update() method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message. In these cases you might instead choose to override .save() directly, as being more readable and meaningful. For example: class ContactForm(serializers.Serializer):\n email = serializers.EmailField()\n message = serializers.CharField()\n\n def save(self):\n email = self.validated_data['email']\n message = self.validated_data['message']\n send_email(from=email, message=message) Note that in the case above we're now having to access the serializer .validated_data property directly.",
+ "text": "If we want to be able to return complete object instances based on the validated data we need to implement one or both of the .create() and update() methods. For example: class CommentSerializer(serializers.Serializer):\n email = serializers.EmailField()\n content = serializers.CharField(max_length=200)\n created = serializers.DateTimeField()\n\n def create(self, validated_data):\n return Comment(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n return instance If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this: def create(self, validated_data):\n return Comment.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n instance.email = validated_data.get('email', instance.email)\n instance.content = validated_data.get('content', instance.content)\n instance.created = validated_data.get('created', instance.created)\n instance.save()\n return instance Now when deserializing data, we can call .save() to return an object instance, based on the validated data. comment = serializer.save() Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: # .save() will create a new instance.\nserializer = CommentSerializer(data=data)\n\n# .save() will update the existing `comment` instance.\nserializer = CommentSerializer(comment, data=data) Both the .create() and .update() methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.",
"title": "Saving instances"
},
+ {
+ "location": "/api-guide/serializers/#passing-additional-attributes-to-save",
+ "text": "Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data. You can do so by including additional keyword arguments when calling .save() . For example: serializer.save(owner=request.user) Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.",
+ "title": "Passing additional attributes to .save()"
+ },
+ {
+ "location": "/api-guide/serializers/#overriding-save-directly",
+ "text": "In some cases the .create() and .update() method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message. In these cases you might instead choose to override .save() directly, as being more readable and meaningful. For example: class ContactForm(serializers.Serializer):\n email = serializers.EmailField()\n message = serializers.CharField()\n\n def save(self):\n email = self.validated_data['email']\n message = self.validated_data['message']\n send_email(from=email, message=message) Note that in the case above we're now having to access the serializer .validated_data property directly.",
+ "title": "Overriding .save() directly."
+ },
{
"location": "/api-guide/serializers/#validation",
- "text": "When deserializing data, you always need to call is_valid() before attempting to access the validated data, or save an object instance. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example: serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']} Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The non_field_errors key may also be present, and will list any general validation errors. The name of the non_field_errors key may be customized using the NON_FIELD_ERRORS_KEY REST framework setting. When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items. Raising an exception on invalid data The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors. These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return HTTP 400 Bad Request responses by default. # Return a 400 response if the data was invalid.\nserializer.is_valid(raise_exception=True) Field-level validation You can specify custom field-level validation by adding .validate_ field_name methods to your Serializer subclass. These are similar to the .clean_ field_name methods on Django forms. These methods take a single argument, which is the field value that requires validation. Your validate_ field_name methods should return the validated value or raise a serializers.ValidationError . For example: from rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n title = serializers.CharField(max_length=100)\n content = serializers.CharField()\n\n def validate_title(self, value):\n \"\"\"\n Check that the blog post is about Django.\n \"\"\"\n if 'django' not in value.lower():\n raise serializers.ValidationError(\"Blog post is not about Django\")\n return value Note: If your field_name is declared on your serializer with the parameter required=False then this validation step will not take place if the field is not included. Object-level validation To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is a dictionary of field values. It should raise a ValidationError if necessary, or just return the validated values. For example: from rest_framework import serializers\n\nclass EventSerializer(serializers.Serializer):\n description = serializers.CharField(max_length=100)\n start = serializers.DateTimeField()\n finish = serializers.DateTimeField()\n\n def validate(self, data):\n \"\"\"\n Check that the start is before the stop.\n \"\"\"\n if data['start'] data['finish']:\n raise serializers.ValidationError(\"finish must occur after start\")\n return data Validators Individual fields on a serializer can include validators, by declaring them on the field instance, for example: def multiple_of_ten(value):\n if value % 10 != 0:\n raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n score = IntegerField(validators=[multiple_of_ten])\n ... Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner Meta class, like so: class EventSerializer(serializers.Serializer):\n name = serializers.CharField()\n room_number = serializers.IntegerField(choices=[101, 102, 103, 201])\n date = serializers.DateField()\n\n class Meta:\n # Each room only has one event per day.\n validators = UniqueTogetherValidator(\n queryset=Event.objects.all(),\n fields=['room_number', 'date']\n ) For more information see the validators documentation .",
+ "text": "When deserializing data, you always need to call is_valid() before attempting to access the validated data, or save an object instance. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example: serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']} Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The non_field_errors key may also be present, and will list any general validation errors. The name of the non_field_errors key may be customized using the NON_FIELD_ERRORS_KEY REST framework setting. When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.",
"title": "Validation"
},
+ {
+ "location": "/api-guide/serializers/#raising-an-exception-on-invalid-data",
+ "text": "The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors. These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return HTTP 400 Bad Request responses by default. # Return a 400 response if the data was invalid.\nserializer.is_valid(raise_exception=True)",
+ "title": "Raising an exception on invalid data"
+ },
+ {
+ "location": "/api-guide/serializers/#field-level-validation",
+ "text": "You can specify custom field-level validation by adding .validate_ field_name methods to your Serializer subclass. These are similar to the .clean_ field_name methods on Django forms. These methods take a single argument, which is the field value that requires validation. Your validate_ field_name methods should return the validated value or raise a serializers.ValidationError . For example: from rest_framework import serializers\n\nclass BlogPostSerializer(serializers.Serializer):\n title = serializers.CharField(max_length=100)\n content = serializers.CharField()\n\n def validate_title(self, value):\n \"\"\"\n Check that the blog post is about Django.\n \"\"\"\n if 'django' not in value.lower():\n raise serializers.ValidationError(\"Blog post is not about Django\")\n return value Note: If your field_name is declared on your serializer with the parameter required=False then this validation step will not take place if the field is not included.",
+ "title": "Field-level validation"
+ },
+ {
+ "location": "/api-guide/serializers/#object-level-validation",
+ "text": "To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is a dictionary of field values. It should raise a ValidationError if necessary, or just return the validated values. For example: from rest_framework import serializers\n\nclass EventSerializer(serializers.Serializer):\n description = serializers.CharField(max_length=100)\n start = serializers.DateTimeField()\n finish = serializers.DateTimeField()\n\n def validate(self, data):\n \"\"\"\n Check that the start is before the stop.\n \"\"\"\n if data['start'] data['finish']:\n raise serializers.ValidationError(\"finish must occur after start\")\n return data",
+ "title": "Object-level validation"
+ },
+ {
+ "location": "/api-guide/serializers/#validators",
+ "text": "Individual fields on a serializer can include validators, by declaring them on the field instance, for example: def multiple_of_ten(value):\n if value % 10 != 0:\n raise serializers.ValidationError('Not a multiple of ten')\n\nclass GameRecord(serializers.Serializer):\n score = IntegerField(validators=[multiple_of_ten])\n ... Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner Meta class, like so: class EventSerializer(serializers.Serializer):\n name = serializers.CharField()\n room_number = serializers.IntegerField(choices=[101, 102, 103, 201])\n date = serializers.DateField()\n\n class Meta:\n # Each room only has one event per day.\n validators = UniqueTogetherValidator(\n queryset=Event.objects.all(),\n fields=['room_number', 'date']\n ) For more information see the validators documentation .",
+ "title": "Validators"
+ },
{
"location": "/api-guide/serializers/#accessing-the-initial-data-and-instance",
"text": "When passing an initial object or queryset to a serializer instance, the object will be made available as .instance . If no initial object is passed then the .instance attribute will be None . When passing data to a serializer instance, the unmodified data will be made available as .initial_data . If the data keyword argument is not passed then the .initial_data attribute will not exist.",
@@ -1127,14 +1382,39 @@
},
{
"location": "/api-guide/serializers/#writable-nested-representations",
- "text": "When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object. serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']} Similarly, the .validated_data property will include nested data structures. Writing .create() methods for nested representations If you're supporting writable nested representations you'll need to write .create() or .update() methods that handle saving multiple objects. The following example demonstrates how you might handle creating a user with a nested profile object. class UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user Writing .update() methods for nested representations For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is None , or not provided, which of the following should occur? Set the relationship to NULL in the database. Delete the associated instance. Ignore the data and leave the instance as it is. Raise a validation error. Here's an example for an update() method on our previous UserSerializer class. def update(self, instance, validated_data):\n profile_data = validated_data.pop('profile')\n # Unless the application properly enforces that this field is\n # always set, the follow could raise a `DoesNotExist`, which\n # would need to be handled.\n profile = instance.profile\n\n instance.username = validated_data.get('username', instance.username)\n instance.email = validated_data.get('email', instance.email)\n instance.save()\n\n profile.is_premium_member = profile_data.get(\n 'is_premium_member',\n profile.is_premium_member\n )\n profile.has_support_contract = profile_data.get(\n 'has_support_contract',\n profile.has_support_contract\n )\n profile.save()\n\n return instance Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default ModelSerializer .create() and .update() methods do not include support for writable nested representations. It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release. Handling saving related instances in model manager classes An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances. For example, suppose we wanted to ensure that User instances and Profile instances are always created together as a pair. We might write a custom manager class that looks something like this: class UserManager(models.Manager):\n ...\n\n def create(self, username, email, is_premium_member=False, has_support_contract=False):\n user = User(username=username, email=email)\n user.save()\n profile = Profile(\n user=user,\n is_premium_member=is_premium_member,\n has_support_contract=has_support_contract\n )\n profile.save()\n return user This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our .create() method on the serializer class can now be re-written to use the new manager method. def create(self, validated_data):\n return User.objects.create(\n username=validated_data['username'],\n email=validated_data['email']\n is_premium_member=validated_data['profile']['is_premium_member']\n has_support_contract=validated_data['profile']['has_support_contract']\n ) For more details on this approach see the Django documentation on model managers , and this blogpost on using model and manager classes .",
+ "text": "When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object. serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})\nserializer.is_valid()\n# False\nserializer.errors\n# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']} Similarly, the .validated_data property will include nested data structures.",
"title": "Writable nested representations"
},
+ {
+ "location": "/api-guide/serializers/#writing-create-methods-for-nested-representations",
+ "text": "If you're supporting writable nested representations you'll need to write .create() or .update() methods that handle saving multiple objects. The following example demonstrates how you might handle creating a user with a nested profile object. class UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user",
+ "title": "Writing .create() methods for nested representations"
+ },
+ {
+ "location": "/api-guide/serializers/#writing-update-methods-for-nested-representations",
+ "text": "For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is None , or not provided, which of the following should occur? Set the relationship to NULL in the database. Delete the associated instance. Ignore the data and leave the instance as it is. Raise a validation error. Here's an example for an update() method on our previous UserSerializer class. def update(self, instance, validated_data):\n profile_data = validated_data.pop('profile')\n # Unless the application properly enforces that this field is\n # always set, the follow could raise a `DoesNotExist`, which\n # would need to be handled.\n profile = instance.profile\n\n instance.username = validated_data.get('username', instance.username)\n instance.email = validated_data.get('email', instance.email)\n instance.save()\n\n profile.is_premium_member = profile_data.get(\n 'is_premium_member',\n profile.is_premium_member\n )\n profile.has_support_contract = profile_data.get(\n 'has_support_contract',\n profile.has_support_contract\n )\n profile.save()\n\n return instance Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default ModelSerializer .create() and .update() methods do not include support for writable nested representations. It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.",
+ "title": "Writing .update() methods for nested representations"
+ },
+ {
+ "location": "/api-guide/serializers/#handling-saving-related-instances-in-model-manager-classes",
+ "text": "An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances. For example, suppose we wanted to ensure that User instances and Profile instances are always created together as a pair. We might write a custom manager class that looks something like this: class UserManager(models.Manager):\n ...\n\n def create(self, username, email, is_premium_member=False, has_support_contract=False):\n user = User(username=username, email=email)\n user.save()\n profile = Profile(\n user=user,\n is_premium_member=is_premium_member,\n has_support_contract=has_support_contract\n )\n profile.save()\n return user This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our .create() method on the serializer class can now be re-written to use the new manager method. def create(self, validated_data):\n return User.objects.create(\n username=validated_data['username'],\n email=validated_data['email']\n is_premium_member=validated_data['profile']['is_premium_member']\n has_support_contract=validated_data['profile']['has_support_contract']\n ) For more details on this approach see the Django documentation on model managers , and this blogpost on using model and manager classes .",
+ "title": "Handling saving related instances in model manager classes"
+ },
{
"location": "/api-guide/serializers/#dealing-with-multiple-objects",
- "text": "The Serializer class can also handle serializing or deserializing lists of objects. Serializing multiple objects To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized. queryset = Book.objects.all()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ] Deserializing multiple objects The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the ListSerializer documentation below.",
+ "text": "The Serializer class can also handle serializing or deserializing lists of objects.",
"title": "Dealing with multiple objects"
},
+ {
+ "location": "/api-guide/serializers/#serializing-multiple-objects",
+ "text": "To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized. queryset = Book.objects.all()\nserializer = BookSerializer(queryset, many=True)\nserializer.data\n# [\n# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},\n# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},\n# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}\n# ]",
+ "title": "Serializing multiple objects"
+ },
+ {
+ "location": "/api-guide/serializers/#deserializing-multiple-objects",
+ "text": "The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the ListSerializer documentation below.",
+ "title": "Deserializing multiple objects"
+ },
{
"location": "/api-guide/serializers/#including-extra-context",
"text": "There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs. You can provide arbitrary additional context by passing a context argument when instantiating the serializer. For example: serializer = AccountSerializer(account, context={'request': request})\nserializer.data\n# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'} The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.",
@@ -1142,9 +1422,14 @@
},
{
"location": "/api-guide/serializers/#modelserializer",
- "text": "Often you'll want serializer classes that map closely to Django model definitions. The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that : It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .create() and .update() . Declaring a ModelSerializer looks like this: class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created') By default, all the model fields on the class will be mapped to a corresponding serializer fields. Any relationships such as foreign keys on the model will be mapped to PrimaryKeyRelatedField . Reverse relationships are not included by default unless explicitly included as described below. Inspecting a ModelSerializer Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with ModelSerializers where you want to determine what set of fields and validators are being automatically created for you. To do so, open the Django shell, using python manage.py shell , then import the serializer class, instantiate it, and print the object representation\u2026 from myapp.serializers import AccountSerializer serializer = AccountSerializer() print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())",
+ "text": "Often you'll want serializer classes that map closely to Django model definitions. The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that : It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .create() and .update() . Declaring a ModelSerializer looks like this: class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created') By default, all the model fields on the class will be mapped to a corresponding serializer fields. Any relationships such as foreign keys on the model will be mapped to PrimaryKeyRelatedField . Reverse relationships are not included by default unless explicitly included as described below.",
"title": "ModelSerializer"
},
+ {
+ "location": "/api-guide/serializers/#inspecting-a-modelserializer",
+ "text": "Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with ModelSerializers where you want to determine what set of fields and validators are being automatically created for you. To do so, open the Django shell, using python manage.py shell , then import the serializer class, instantiate it, and print the object representation\u2026 from myapp.serializers import AccountSerializer serializer = AccountSerializer() print(repr(serializer))\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())",
+ "title": "Inspecting a ModelSerializer"
+ },
{
"location": "/api-guide/serializers/#specifying-which-fields-to-include",
"text": "If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm . It is strongly recommended that you explicitly set all fields that should be serialized using the fields attribute. This will make it less likely to result in unintentionally exposing data when your models change. For example: class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'users', 'created') You can also set the fields attribute to the special value '__all__' to indicate that all fields in the model should be used. For example: class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = '__all__' You can set the exclude attribute to a list of fields to be excluded from the serializer. For example: class AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n exclude = ('users',) In the example above, if the Account model had 3 fields account_name , users , and created , this will result in the fields account_name and created to be serialized. The names in the fields and exclude attributes will normally map to model fields on the model class. Alternatively names in the fields options can map to properties or methods which take no arguments that exist on the model class.",
@@ -1182,14 +1467,74 @@
},
{
"location": "/api-guide/serializers/#customizing-field-mappings",
- "text": "The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer. Normally if a ModelSerializer does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular Serializer class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model. .serializer_field_mapping A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class. .serializer_related_field This property should be the serializer field class, that is used for relational fields by default. For ModelSerializer this defaults to PrimaryKeyRelatedField . For HyperlinkedModelSerializer this defaults to serializers.HyperlinkedRelatedField . serializer_url_field The serializer field class that should be used for any url field on the serializer. Defaults to serializers.HyperlinkedIdentityField serializer_choice_field The serializer field class that should be used for any choice fields on the serializer. Defaults to serializers.ChoiceField The field_class and field_kwargs API The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of (field_class, field_kwargs) . .build_standard_field(self, field_name, model_field) Called to generate a serializer field that maps to a standard model field. The default implementation returns a serializer class based on the serializer_field_mapping attribute. .build_relational_field(self, field_name, relation_info) Called to generate a serializer field that maps to a relational model field. The default implementation returns a serializer class based on the serializer_relational_field attribute. The relation_info argument is a named tuple, that contains model_field , related_model , to_many and has_through_model properties. .build_nested_field(self, field_name, relation_info, nested_depth) Called to generate a serializer field that maps to a relational model field, when the depth option has been set. The default implementation dynamically creates a nested serializer class based on either ModelSerializer or HyperlinkedModelSerializer . The nested_depth will be the value of the depth option, minus one. The relation_info argument is a named tuple, that contains model_field , related_model , to_many and has_through_model properties. .build_property_field(self, field_name, model_class) Called to generate a serializer field that maps to a property or zero-argument method on the model class. The default implementation returns a ReadOnlyField class. .build_url_field(self, field_name, model_class) Called to generate a serializer field for the serializer's own url field. The default implementation returns a HyperlinkedIdentityField class. .build_unknown_field(self, field_name, model_class) Called when the field name did not map to any model field or model property.\nThe default implementation raises an error, although subclasses may customize this behavior.",
+ "text": "The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer. Normally if a ModelSerializer does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular Serializer class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.",
"title": "Customizing field mappings"
},
+ {
+ "location": "/api-guide/serializers/#serializer_field_mapping",
+ "text": "A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class.",
+ "title": ".serializer_field_mapping"
+ },
+ {
+ "location": "/api-guide/serializers/#serializer_related_field",
+ "text": "This property should be the serializer field class, that is used for relational fields by default. For ModelSerializer this defaults to PrimaryKeyRelatedField . For HyperlinkedModelSerializer this defaults to serializers.HyperlinkedRelatedField .",
+ "title": ".serializer_related_field"
+ },
+ {
+ "location": "/api-guide/serializers/#serializer_url_field",
+ "text": "The serializer field class that should be used for any url field on the serializer. Defaults to serializers.HyperlinkedIdentityField",
+ "title": "serializer_url_field"
+ },
+ {
+ "location": "/api-guide/serializers/#serializer_choice_field",
+ "text": "The serializer field class that should be used for any choice fields on the serializer. Defaults to serializers.ChoiceField",
+ "title": "serializer_choice_field"
+ },
+ {
+ "location": "/api-guide/serializers/#the-field_class-and-field_kwargs-api",
+ "text": "The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of (field_class, field_kwargs) .",
+ "title": "The field_class and field_kwargs API"
+ },
+ {
+ "location": "/api-guide/serializers/#build_standard_fieldself-field_name-model_field",
+ "text": "Called to generate a serializer field that maps to a standard model field. The default implementation returns a serializer class based on the serializer_field_mapping attribute.",
+ "title": ".build_standard_field(self, field_name, model_field)"
+ },
+ {
+ "location": "/api-guide/serializers/#build_relational_fieldself-field_name-relation_info",
+ "text": "Called to generate a serializer field that maps to a relational model field. The default implementation returns a serializer class based on the serializer_relational_field attribute. The relation_info argument is a named tuple, that contains model_field , related_model , to_many and has_through_model properties.",
+ "title": ".build_relational_field(self, field_name, relation_info)"
+ },
+ {
+ "location": "/api-guide/serializers/#build_nested_fieldself-field_name-relation_info-nested_depth",
+ "text": "Called to generate a serializer field that maps to a relational model field, when the depth option has been set. The default implementation dynamically creates a nested serializer class based on either ModelSerializer or HyperlinkedModelSerializer . The nested_depth will be the value of the depth option, minus one. The relation_info argument is a named tuple, that contains model_field , related_model , to_many and has_through_model properties.",
+ "title": ".build_nested_field(self, field_name, relation_info, nested_depth)"
+ },
+ {
+ "location": "/api-guide/serializers/#build_property_fieldself-field_name-model_class",
+ "text": "Called to generate a serializer field that maps to a property or zero-argument method on the model class. The default implementation returns a ReadOnlyField class.",
+ "title": ".build_property_field(self, field_name, model_class)"
+ },
+ {
+ "location": "/api-guide/serializers/#build_url_fieldself-field_name-model_class",
+ "text": "Called to generate a serializer field for the serializer's own url field. The default implementation returns a HyperlinkedIdentityField class.",
+ "title": ".build_url_field(self, field_name, model_class)"
+ },
+ {
+ "location": "/api-guide/serializers/#build_unknown_fieldself-field_name-model_class",
+ "text": "Called when the field name did not map to any model field or model property.\nThe default implementation raises an error, although subclasses may customize this behavior.",
+ "title": ".build_unknown_field(self, field_name, model_class)"
+ },
{
"location": "/api-guide/serializers/#hyperlinkedmodelserializer",
"text": "The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field. You can explicitly include the primary key by adding it to the fields option, for example: class AccountSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Account\n fields = ('url', 'id', 'account_name', 'users', 'created')",
"title": "HyperlinkedModelSerializer"
},
+ {
+ "location": "/api-guide/serializers/#absolute-and-relative-urls",
+ "text": "When instantiating a HyperlinkedModelSerializer you must include the current request in the serializer context, for example: serializer = AccountSerializer(queryset, context={'request': request}) Doing so will ensure that the hyperlinks can include an appropriate hostname,\nso that the resulting representation uses fully qualified URLs, such as: http://api.example.com/accounts/1/ Rather than relative URLs, such as: /accounts/1/ If you do want to use relative URLs, you should explicitly pass {'request': None} \nin the serializer context.",
+ "title": "Absolute and relative URLs"
+ },
{
"location": "/api-guide/serializers/#how-hyperlinked-views-are-determined",
"text": "There needs to be a way of determining which views should be used for hyperlinking to model instances. By default hyperlinks are expected to correspond to a view name that matches the style '{model_name}-detail' , and looks up the instance by a pk keyword argument. You can override a URL field view name and lookup field by using either, or both of, the view_name and lookup_field options in the extra_kwargs setting, like so: class AccountSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Account\n fields = ('account_url', 'account_name', 'users', 'created')\n extra_kwargs = {\n 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}\n 'users': {'lookup_field': 'username'}\n } Alternatively you can set the fields on the serializer explicitly. For example: class AccountSerializer(serializers.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='accounts',\n lookup_field='slug'\n )\n users = serializers.HyperlinkedRelatedField(\n view_name='user-detail',\n lookup_field='username',\n many=True,\n read_only=True\n )\n\n class Meta:\n model = Account\n fields = ('url', 'account_name', 'users', 'created') Tip : Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the repr of a HyperlinkedModelSerializer instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.",
@@ -1202,14 +1547,54 @@
},
{
"location": "/api-guide/serializers/#listserializer",
- "text": "The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer. When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer The following argument can also be passed to a ListSerializer field or a serializer that is passed many=True : allow_empty This is True by default, but can be set to False if you want to disallow empty lists as valid input. Customizing ListSerializer behavior There are a few use cases when you might want to customize the ListSerializer behavior. For example: You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list. You want to customize the create or update behavior of multiple objects. For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class. For example: class CustomListSerializer(serializers.ListSerializer):\n ...\n\nclass CustomSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = CustomListSerializer Customizing multiple create The default implementation for multiple object creation is to simply call .create() for each item in the list. If you want to customize this behavior, you'll need to customize the .create() method on ListSerializer class that is used when many=True is passed. For example: class BookListSerializer(serializers.ListSerializer):\n def create(self, validated_data):\n books = [Book(**item) for item in validated_data]\n return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = BookListSerializer Customizing multiple update By default the ListSerializer class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous. To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind: How do you determine which instance should be updated for each item in the list of data? How should insertions be handled? Are they invalid, or do they create new objects? How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid? How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? You will need to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only . This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's update method. Here's an example of how you might choose to implement multiple updates: class BookListSerializer(serializers.ListSerializer):\n def update(self, instance, validated_data):\n # Maps for id- instance and id- data item.\n book_mapping = {book.id: book for book in instance}\n data_mapping = {item['id']: item for item in validated_data}\n\n # Perform creations and updates.\n ret = []\n for book_id, data in data_mapping.items():\n book = book_mapping.get(book_id, None)\n if book is None:\n ret.append(self.child.create(data))\n else:\n ret.append(self.child.update(book, data))\n\n # Perform deletions.\n for book_id, book in book_mapping.items():\n if book_id not in data_mapping:\n book.delete()\n\n return ret\n\nclass BookSerializer(serializers.Serializer):\n # We need to identify elements in the list using their primary key,\n # so use a writable field here, rather than the default which would be read-only.\n id = serializers.IntegerField()\n\n ...\n id = serializers.IntegerField(required=False)\n\n class Meta:\n list_serializer_class = BookListSerializer It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the allow_add_remove behavior that was present in REST framework 2. Customizing ListSerializer initialization When a serializer with many=True is instantiated, we need to determine which arguments and keyword arguments should be passed to the .__init__() method for both the child Serializer class, and for the parent ListSerializer class. The default implementation is to pass all arguments to both classes, except for validators , and any custom keyword arguments, both of which are assumed to be intended for the child serializer class. Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when many=True is passed. You can do so by using the many_init class method. @classmethod\n def many_init(cls, *args, **kwargs):\n # Instantiate the child serializer.\n kwargs['child'] = cls()\n # Instantiate the parent list serializer.\n return CustomListSerializer(*args, **kwargs)",
+ "text": "The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer. When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer The following argument can also be passed to a ListSerializer field or a serializer that is passed many=True :",
"title": "ListSerializer"
},
+ {
+ "location": "/api-guide/serializers/#allow_empty",
+ "text": "This is True by default, but can be set to False if you want to disallow empty lists as valid input.",
+ "title": "allow_empty"
+ },
+ {
+ "location": "/api-guide/serializers/#customizing-listserializer-behavior",
+ "text": "There are a few use cases when you might want to customize the ListSerializer behavior. For example: You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list. You want to customize the create or update behavior of multiple objects. For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class. For example: class CustomListSerializer(serializers.ListSerializer):\n ...\n\nclass CustomSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = CustomListSerializer",
+ "title": "Customizing ListSerializer behavior"
+ },
+ {
+ "location": "/api-guide/serializers/#customizing-multiple-create",
+ "text": "The default implementation for multiple object creation is to simply call .create() for each item in the list. If you want to customize this behavior, you'll need to customize the .create() method on ListSerializer class that is used when many=True is passed. For example: class BookListSerializer(serializers.ListSerializer):\n def create(self, validated_data):\n books = [Book(**item) for item in validated_data]\n return Book.objects.bulk_create(books)\n\nclass BookSerializer(serializers.Serializer):\n ...\n class Meta:\n list_serializer_class = BookListSerializer",
+ "title": "Customizing multiple create"
+ },
+ {
+ "location": "/api-guide/serializers/#customizing-multiple-update",
+ "text": "By default the ListSerializer class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous. To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind: How do you determine which instance should be updated for each item in the list of data? How should insertions be handled? Are they invalid, or do they create new objects? How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid? How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? You will need to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only . This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's update method. Here's an example of how you might choose to implement multiple updates: class BookListSerializer(serializers.ListSerializer):\n def update(self, instance, validated_data):\n # Maps for id- instance and id- data item.\n book_mapping = {book.id: book for book in instance}\n data_mapping = {item['id']: item for item in validated_data}\n\n # Perform creations and updates.\n ret = []\n for book_id, data in data_mapping.items():\n book = book_mapping.get(book_id, None)\n if book is None:\n ret.append(self.child.create(data))\n else:\n ret.append(self.child.update(book, data))\n\n # Perform deletions.\n for book_id, book in book_mapping.items():\n if book_id not in data_mapping:\n book.delete()\n\n return ret\n\nclass BookSerializer(serializers.Serializer):\n # We need to identify elements in the list using their primary key,\n # so use a writable field here, rather than the default which would be read-only.\n id = serializers.IntegerField()\n\n ...\n id = serializers.IntegerField(required=False)\n\n class Meta:\n list_serializer_class = BookListSerializer It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the allow_add_remove behavior that was present in REST framework 2.",
+ "title": "Customizing multiple update"
+ },
+ {
+ "location": "/api-guide/serializers/#customizing-listserializer-initialization",
+ "text": "When a serializer with many=True is instantiated, we need to determine which arguments and keyword arguments should be passed to the .__init__() method for both the child Serializer class, and for the parent ListSerializer class. The default implementation is to pass all arguments to both classes, except for validators , and any custom keyword arguments, both of which are assumed to be intended for the child serializer class. Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when many=True is passed. You can do so by using the many_init class method. @classmethod\n def many_init(cls, *args, **kwargs):\n # Instantiate the child serializer.\n kwargs['child'] = cls()\n # Instantiate the parent list serializer.\n return CustomListSerializer(*args, **kwargs)",
+ "title": "Customizing ListSerializer initialization"
+ },
{
"location": "/api-guide/serializers/#baseserializer",
- "text": "BaseSerializer class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the Serializer class: .data - Returns the outgoing primitive representation. .is_valid() - Deserializes and validates incoming data. .validated_data - Returns the validated incoming data. .errors - Returns any errors during validation. .save() - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: .to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations. .create() and .update() - Override either or both of these to support saving instances. Because this class provides the same interface as the Serializer class, you can use it with the existing generic class based views exactly as you would for a regular Serializer or ModelSerializer . The only difference you'll notice when doing so is the BaseSerializer 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. Read-only BaseSerializer classes To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model: class HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField() It's simple to create a read-only serializer for converting HighScore instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n } We can now use this class to serialize single HighScore instances: @api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data) Or use it to serialize multiple instances: @api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data) Read-write BaseSerializer classes To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format. Once you've implemented .to_internal_value() , the basic validation API will be available on the serializer, and you will be able to use .is_valid() , .validated_data and .errors . If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods. Here's a complete example of our previous HighScoreSerializer , that's been updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data) Creating new base classes The BaseSerializer 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. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)",
+ "text": "BaseSerializer class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the Serializer class: .data - Returns the outgoing primitive representation. .is_valid() - Deserializes and validates incoming data. .validated_data - Returns the validated incoming data. .errors - Returns any errors during validation. .save() - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: .to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations. .create() and .update() - Override either or both of these to support saving instances. Because this class provides the same interface as the Serializer class, you can use it with the existing generic class based views exactly as you would for a regular Serializer or ModelSerializer . The only difference you'll notice when doing so is the BaseSerializer 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.",
"title": "BaseSerializer"
},
+ {
+ "location": "/api-guide/serializers/#read-only-baseserializer-classes",
+ "text": "To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model: class HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField() It's simple to create a read-only serializer for converting HighScore instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n } We can now use this class to serialize single HighScore instances: @api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data) Or use it to serialize multiple instances: @api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)",
+ "title": "Read-only BaseSerializer classes"
+ },
+ {
+ "location": "/api-guide/serializers/#read-write-baseserializer-classes",
+ "text": "To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format. Once you've implemented .to_internal_value() , the basic validation API will be available on the serializer, and you will be able to use .is_valid() , .validated_data and .errors . If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods. Here's a complete example of our previous HighScoreSerializer , that's been updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)",
+ "title": "Read-write BaseSerializer classes"
+ },
+ {
+ "location": "/api-guide/serializers/#creating-new-base-classes",
+ "text": "The BaseSerializer 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. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)",
+ "title": "Creating new base classes"
+ },
{
"location": "/api-guide/serializers/#advanced-serializer-usage",
"text": "",
@@ -1217,14 +1602,29 @@
},
{
"location": "/api-guide/serializers/#overriding-serialization-and-deserialization-behavior",
- "text": "If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the .to_representation() or .to_internal_value() methods. Some reasons this might be useful include... Adding new behavior for new serializer base classes. Modifying the behavior slightly for an existing class. Improving serialization performance for a frequently accessed API endpoint that returns lots of data. The signatures for these methods are as follows: .to_representation(self, obj) Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API. .to_internal_value(self, data) Takes the unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data . The return value will also be passed to the .create() or .update() methods if .save() is called on the serializer class. If any of the validation fails, then the method should raise a serializers.ValidationError(errors) . Typically the errors argument here will be a dictionary mapping field names to error messages. The data argument passed to this method will normally be the value of request.data , so the datatype it provides will depend on the parser classes you have configured for your API.",
+ "text": "If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the .to_representation() or .to_internal_value() methods. Some reasons this might be useful include... Adding new behavior for new serializer base classes. Modifying the behavior slightly for an existing class. Improving serialization performance for a frequently accessed API endpoint that returns lots of data. The signatures for these methods are as follows:",
"title": "Overriding serialization and deserialization behavior"
},
+ {
+ "location": "/api-guide/serializers/#to_representationself-obj",
+ "text": "Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.",
+ "title": ".to_representation(self, obj)"
+ },
+ {
+ "location": "/api-guide/serializers/#to_internal_valueself-data",
+ "text": "Takes the unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data . The return value will also be passed to the .create() or .update() methods if .save() is called on the serializer class. If any of the validation fails, then the method should raise a serializers.ValidationError(errors) . Typically the errors argument here will be a dictionary mapping field names to error messages. The data argument passed to this method will normally be the value of request.data , so the datatype it provides will depend on the parser classes you have configured for your API.",
+ "title": ".to_internal_value(self, data)"
+ },
{
"location": "/api-guide/serializers/#dynamically-modifying-fields",
- "text": "Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the .fields attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer. Modifying the fields argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer. Example For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so: class DynamicFieldsModelSerializer(serializers.ModelSerializer):\n \"\"\"\n A ModelSerializer that takes an additional `fields` argument that\n controls which fields should be displayed.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Don't pass the 'fields' arg up to the superclass\n fields = kwargs.pop('fields', None)\n\n # Instantiate the superclass normally\n super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)\n\n if fields is not None:\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(fields)\n existing = set(self.fields.keys())\n for field_name in existing - allowed:\n self.fields.pop(field_name) This would then allow you to do the following: class UserSerializer(DynamicFieldsModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} print UserSerializer(user, fields=('id', 'email'))\n{'id': 2, 'email': 'jon@example.com'}",
+ "text": "Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the .fields attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer. Modifying the fields argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.",
"title": "Dynamically modifying fields"
},
+ {
+ "location": "/api-guide/serializers/#example",
+ "text": "For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so: class DynamicFieldsModelSerializer(serializers.ModelSerializer):\n \"\"\"\n A ModelSerializer that takes an additional `fields` argument that\n controls which fields should be displayed.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Don't pass the 'fields' arg up to the superclass\n fields = kwargs.pop('fields', None)\n\n # Instantiate the superclass normally\n super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)\n\n if fields is not None:\n # Drop any fields that are not specified in the `fields` argument.\n allowed = set(fields)\n existing = set(self.fields.keys())\n for field_name in existing - allowed:\n self.fields.pop(field_name) This would then allow you to do the following: class UserSerializer(DynamicFieldsModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') print UserSerializer(user)\n{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} print UserSerializer(user, fields=('id', 'email'))\n{'id': 2, 'email': 'jon@example.com'}",
+ "title": "Example"
+ },
{
"location": "/api-guide/serializers/#customizing-the-default-fields",
"text": "REST framework 2 provided an API to allow developers to override how a ModelSerializer class would automatically generate the default set of fields. This API included the .get_field() , .get_pk_field() and other methods. Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change. A new interface for controlling this behavior is currently planned for REST framework 3.1.",
@@ -1272,7 +1672,7 @@
},
{
"location": "/api-guide/fields/",
- "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.\n\n\nMay be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a \nset_context\n method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for \nvalidators\n.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field. May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django \nField\n:\n\n\nimport datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)\n\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n)\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n. Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included. Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nIn the case of JSON this means the default datetime representation uses the \nECMA 262 date time string specification\n. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: \n2013-01-29T12:34:56.123Z\n.\n\n\nauto_now\n and \nauto_now_add\n model fields.\n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer. For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation. Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package. The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n child = CharField()\n\n\n\nJSONField\n\n\nA field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, is \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model. For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red \n= 0 and green \n= 0 and blue \n= 0)\n assert(red \n 256 and green \n 256 and blue \n 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used to represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.",
+ "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.\n\n\nMay be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a \nset_context\n method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for \nvalidators\n.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field. May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django \nField\n:\n\n\nimport datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)\n\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n)\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n. Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included. Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nIn the case of JSON this means the default datetime representation uses the \nECMA 262 date time string specification\n. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: \n2013-01-29T12:34:56.123Z\n.\n\n\nauto_now_add\n model fields.\nauto_now\n and \n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer. For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=None, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation. Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package. The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n child = CharField()\n\n\n\nJSONField\n\n\nA field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, is \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model. For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red \n= 0 and green \n= 0 and blue \n= 0)\n assert(red \n 256 and green \n 256 and blue \n 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used to represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.",
"title": "Serializer fields"
},
{
@@ -1282,9 +1682,69 @@
},
{
"location": "/api-guide/fields/#core-arguments",
- "text": "Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: read_only Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. Defaults to False write_only Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to False required Normally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization. Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. Defaults to True . allow_null Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Defaults to False default If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a set_context method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators . Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error. source The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url') , or may use dotted notation to traverse attributes, such as EmailField(source='user.email') . The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field. validators A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError , but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages. error_messages A dictionary of error codes to error messages. label A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. help_text A text string that may be used as a description of the field in HTML form fields or other descriptive elements. initial A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django Field : import datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today) style A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are 'input_type' and 'base_template' : # Use input type=\"password\" for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n) For more details see the HTML Forms documentation.",
+ "text": "Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:",
"title": "Core arguments"
},
+ {
+ "location": "/api-guide/fields/#read_only",
+ "text": "Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. Defaults to False",
+ "title": "read_only"
+ },
+ {
+ "location": "/api-guide/fields/#write_only",
+ "text": "Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to False",
+ "title": "write_only"
+ },
+ {
+ "location": "/api-guide/fields/#required",
+ "text": "Normally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization. Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. Defaults to True .",
+ "title": "required"
+ },
+ {
+ "location": "/api-guide/fields/#allow_null",
+ "text": "Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Defaults to False",
+ "title": "allow_null"
+ },
+ {
+ "location": "/api-guide/fields/#default",
+ "text": "If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a set_context method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators . Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.",
+ "title": "default"
+ },
+ {
+ "location": "/api-guide/fields/#source",
+ "text": "The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url') , or may use dotted notation to traverse attributes, such as EmailField(source='user.email') . The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. Defaults to the name of the field.",
+ "title": "source"
+ },
+ {
+ "location": "/api-guide/fields/#validators",
+ "text": "A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError , but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages.",
+ "title": "validators"
+ },
+ {
+ "location": "/api-guide/fields/#error_messages",
+ "text": "A dictionary of error codes to error messages.",
+ "title": "error_messages"
+ },
+ {
+ "location": "/api-guide/fields/#label",
+ "text": "A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.",
+ "title": "label"
+ },
+ {
+ "location": "/api-guide/fields/#help_text",
+ "text": "A text string that may be used as a description of the field in HTML form fields or other descriptive elements.",
+ "title": "help_text"
+ },
+ {
+ "location": "/api-guide/fields/#initial",
+ "text": "A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django Field : import datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)",
+ "title": "initial"
+ },
+ {
+ "location": "/api-guide/fields/#style",
+ "text": "A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are 'input_type' and 'base_template' : # Use input type=\"password\" for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n) For more details see the HTML Forms documentation.",
+ "title": "style"
+ },
{
"location": "/api-guide/fields/#boolean-fields",
"text": "",
@@ -1362,9 +1822,14 @@
},
{
"location": "/api-guide/fields/#decimalfield",
- "text": "A decimal representation, represented in Python by a Decimal instance. Corresponds to django.db.models.fields.DecimalField . Signature : DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. decimal_places The number of decimal places to store with the number. coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value. Example usage To validate numbers up to 999 with a resolution of 2 decimal places, you would use: serializers.DecimalField(max_digits=5, decimal_places=2) And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) This field also takes an optional argument, coerce_to_string . If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer. If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.",
+ "text": "A decimal representation, represented in Python by a Decimal instance. Corresponds to django.db.models.fields.DecimalField . Signature : DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. decimal_places The number of decimal places to store with the number. coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. max_value Validate that the number provided is no greater than this value. min_value Validate that the number provided is no less than this value.",
"title": "DecimalField"
},
+ {
+ "location": "/api-guide/fields/#example-usage",
+ "text": "To validate numbers up to 999 with a resolution of 2 decimal places, you would use: serializers.DecimalField(max_digits=5, decimal_places=2) And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) This field also takes an optional argument, coerce_to_string . If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer. If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.",
+ "title": "Example usage"
+ },
{
"location": "/api-guide/fields/#date-and-time-fields",
"text": "",
@@ -1372,19 +1837,39 @@
},
{
"location": "/api-guide/fields/#datetimefield",
- "text": "A date and time representation. Corresponds to django.db.models.fields.DateTimeField . Signature: DateTimeField(format=None, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation . In this case the datetime encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] . DateTimeField format strings. Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z' ) When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class. In the case of JSON this means the default datetime representation uses the ECMA 262 date time string specification . This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: 2013-01-29T12:34:56.123Z . auto_now and auto_now_add model fields. When using ModelSerializer or HyperlinkedModelSerializer , note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default. If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment",
+ "text": "A date and time representation. Corresponds to django.db.models.fields.DateTimeField . Signature: DateTimeField(format=None, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation . In this case the datetime encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] .",
"title": "DateTimeField"
},
+ {
+ "location": "/api-guide/fields/#datetimefield-format-strings",
+ "text": "Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z' ) When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class. In the case of JSON this means the default datetime representation uses the ECMA 262 date time string specification . This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: 2013-01-29T12:34:56.123Z .",
+ "title": "DateTimeField format strings."
+ },
+ {
+ "location": "/api-guide/fields/#auto_now-and-auto_now_add-model-fields",
+ "text": "When using ModelSerializer or HyperlinkedModelSerializer , note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default. If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment",
+ "title": "auto_now and auto_now_add model fields."
+ },
{
"location": "/api-guide/fields/#datefield",
- "text": "A date representation. Corresponds to django.db.models.fields.DateField Signature: DateField(format=None, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation . In this case the date encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] . DateField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style dates should be used. (eg '2013-01-29' )",
+ "text": "A date representation. Corresponds to django.db.models.fields.DateField Signature: DateField(format=None, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation . In this case the date encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] .",
"title": "DateField"
},
+ {
+ "location": "/api-guide/fields/#datefield-format-strings",
+ "text": "Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style dates should be used. (eg '2013-01-29' )",
+ "title": "DateField format strings"
+ },
{
"location": "/api-guide/fields/#timefield",
- "text": "A time representation. Corresponds to django.db.models.fields.TimeField Signature: TimeField(format=None, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation . In this case the time encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] . TimeField format strings Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000' )",
+ "text": "A time representation. Corresponds to django.db.models.fields.TimeField Signature: TimeField(format=None, input_formats=None) format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation . In this case the time encoding will be determined by the renderer. input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'] .",
"title": "TimeField"
},
+ {
+ "location": "/api-guide/fields/#timefield-format-strings",
+ "text": "Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601' , which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000' )",
+ "title": "TimeField format strings"
+ },
{
"location": "/api-guide/fields/#durationfield",
"text": "A Duration representation.\nCorresponds to django.db.models.fields.DurationField The validated_data for these fields will contain a datetime.timedelta instance.\nThe representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]' . Note: This field is only available with Django versions = 1.8. Signature: DurationField()",
@@ -1407,9 +1892,14 @@
},
{
"location": "/api-guide/fields/#file-upload-fields",
- "text": "Parsers and file uploads. The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser . Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.",
+ "text": "",
"title": "File upload fields"
},
+ {
+ "location": "/api-guide/fields/#parsers-and-file-uploads",
+ "text": "The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser . Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.",
+ "title": "Parsers and file uploads."
+ },
{
"location": "/api-guide/fields/#filefield",
"text": "A file representation. Performs Django's standard FileField validation. Corresponds to django.forms.fields.FileField . Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) max_length - Designates the maximum length for the file name. allow_empty_file - Designates if empty files are allowed. use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.",
@@ -1472,9 +1962,14 @@
},
{
"location": "/api-guide/fields/#examples",
- "text": "Let's look at an example of serializing a class that represents an RGB color value: class Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red = 0 and green = 0 and blue = 0)\n assert(red 256 and green 256 and blue 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue) By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value() . As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__ Raising validation errors Our ColorField class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a serializers.ValidationError , like so: def to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col 255 or col 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue) The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example: default_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col 255 or col 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue) This style keeps you error messages more cleanly separated from your code, and should be preferred.",
+ "text": "Let's look at an example of serializing a class that represents an RGB color value: class Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red = 0 and green = 0 and blue = 0)\n assert(red 256 and green 256 and blue 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue) By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value() . As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__",
"title": "Examples"
},
+ {
+ "location": "/api-guide/fields/#raising-validation-errors",
+ "text": "Our ColorField class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a serializers.ValidationError , like so: def to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col 255 or col 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue) The .fail() method is a shortcut for raising ValidationError that takes a message string from the error_messages dictionary. For example: default_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col 255 or col 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue) This style keeps you error messages more cleanly separated from your code, and should be preferred.",
+ "title": "Raising validation errors"
+ },
{
"location": "/api-guide/fields/#third-party-packages",
"text": "The following third party packages are also available.",
@@ -1512,9 +2007,14 @@
},
{
"location": "/api-guide/relations/#serializer-relations",
- "text": "Bad programmers worry about the code.\nGood programmers worry about data structures and their relationships. Linus Torvalds Relational fields are used to represent model relationships. They can be applied to ForeignKey , ManyToManyField and OneToOneField relationships, as well as to reverse relationships, and custom relationships such as GenericForeignKey . Note: The relational fields are declared in relations.py , but by convention you should import them from the serializers module, using from rest_framework import serializers and refer to fields as serializers. FieldName . Inspecting relationships. When using the ModelSerializer class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style. To do so, open the Django shell, using python manage.py shell , then import the serializer class, instantiate it, and print the object representation\u2026 from myapp.serializers import AccountSerializer serializer = AccountSerializer() print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())",
+ "text": "Bad programmers worry about the code.\nGood programmers worry about data structures and their relationships. Linus Torvalds Relational fields are used to represent model relationships. They can be applied to ForeignKey , ManyToManyField and OneToOneField relationships, as well as to reverse relationships, and custom relationships such as GenericForeignKey . Note: The relational fields are declared in relations.py , but by convention you should import them from the serializers module, using from rest_framework import serializers and refer to fields as serializers. FieldName .",
"title": "Serializer relations"
},
+ {
+ "location": "/api-guide/relations/#inspecting-relationships",
+ "text": "When using the ModelSerializer class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style. To do so, open the Django shell, using python manage.py shell , then import the serializer class, instantiate it, and print the object representation\u2026 from myapp.serializers import AccountSerializer serializer = AccountSerializer() print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.\nAccountSerializer():\n id = IntegerField(label='ID', read_only=True)\n name = CharField(allow_blank=True, max_length=100, required=False)\n owner = PrimaryKeyRelatedField(queryset=User.objects.all())",
+ "title": "Inspecting relationships."
+ },
{
"location": "/api-guide/relations/#api-reference",
"text": "In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. class Album(models.Model):\n album_name = models.CharField(max_length=100)\n artist = models.CharField(max_length=100)\n\nclass Track(models.Model):\n album = models.ForeignKey(Album, related_name='tracks')\n order = models.IntegerField()\n title = models.CharField(max_length=100)\n duration = models.IntegerField()\n\n class Meta:\n unique_together = ('album', 'order')\n ordering = ['order']\n\n def __unicode__(self):\n return '%d: %s' % (self.order, self.title)",
@@ -1632,7 +2132,7 @@
},
{
"location": "/api-guide/validators/",
- "text": "Validators\n\n\n\n\nValidators can be useful for re-using validation logic between different types of fields.\n\n\n \nDjango documentation\n\n\n\n\nMost of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.\n\n\nHowever, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.\n\n\nValidation in REST framework\n\n\nValidation in Django REST framework serializers is handled a little differently to how validation works in Django's \nModelForm\n class.\n\n\nWith \nModelForm\n the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:\n\n\n\n\nIt introduces a proper separation of concerns, making your code behavior more obvious.\n\n\nIt is easy to switch between using shortcut \nModelSerializer\n classes and using explicit \nSerializer\n classes. Any validation behavior being used for \nModelSerializer\n is simple to replicate.\n\n\nPrinting the \nrepr\n of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.\n\n\n\n\nWhen you're using \nModelSerializer\n all of this is handled automatically for you. If you want to drop down to using a \nSerializer\n classes instead, then you need to define the validation rules explicitly.\n\n\nExample\n\n\nAs an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.\n\n\nclass CustomerReportRecord(models.Model):\n time_raised = models.DateTimeField(default=timezone.now, editable=False)\n reference = models.CharField(unique=True, max_length=20)\n description = models.TextField()\n\n\n\nHere's a basic \nModelSerializer\n that we can use for creating or updating instances of \nCustomerReportRecord\n:\n\n\nclass CustomerReportSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomerReportRecord\n\n\n\nIf we open up the Django shell using \nmanage.py shell\n we can now\n\n\n from project.example.serializers import CustomerReportSerializer\n\n serializer = CustomerReportSerializer()\n\n print(repr(serializer))\nCustomerReportSerializer():\n id = IntegerField(label='ID', read_only=True)\n time_raised = DateTimeField(read_only=True)\n reference = CharField(max_length=20, validators=[\nUniqueValidator(queryset=CustomerReportRecord.objects.all())\n])\n description = CharField(style={'type': 'textarea'})\n\n\n\nThe interesting bit here is the \nreference\n field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.\n\n\nBecause of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.\n\n\n\n\nUniqueValidator\n\n\nThis validator can be used to enforce the \nunique=True\n constraint on model fields.\nIt takes a single required argument, and an optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThis validator should be applied to \nserializer fields\n, like so:\n\n\nslug = SlugField(\n max_length=100,\n validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)\n\n\n\nUniqueTogetherValidator\n\n\nThis validator can be used to enforce \nunique_together\n constraints on model instances.\nIt has two required arguments, and a single optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfields\n \nrequired\n - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # ToDo items belong to a parent list, and have an ordering defined\n #\u00a0by the 'position' field. No two items in a given list may share\n # the same position.\n validators = [\n UniqueTogetherValidator(\n queryset=ToDoItem.objects.all(),\n fields=('list', 'position')\n )\n ]\n\n\n\n\n\nNote\n: The \nUniqueTogetherValidation\n class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nUniqueForDateValidator\n\n\nUniqueForMonthValidator\n\n\nUniqueForYearValidator\n\n\nThese validators can be used to enforce the \nunique_for_date\n, \nunique_for_month\n and \nunique_for_year\n constraints on model instances. They take the following arguments:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfield\n \nrequired\n - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.\n\n\ndate_field\n \nrequired\n - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # Blog posts should have a slug that is unique for the current year.\n validators = [\n UniqueForYearValidator(\n queryset=BlogPostItem.objects.all(),\n field='slug',\n date_field='published'\n )\n ]\n\n\n\nThe date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class \ndefault=...\n, because the value being used for the default wouldn't be generated until after the validation has run.\n\n\nThere are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using \nModelSerializer\n you'll probably simply rely on the defaults that REST framework generates for you, but if you are using \nSerializer\n or simply want more explicit control, use on of the styles demonstrated below.\n\n\nUsing with a writable date field.\n\n\nIf you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a \ndefault\n argument, or by setting \nrequired=True\n.\n\n\npublished = serializers.DateTimeField(required=True)\n\n\n\nUsing with a read-only date field.\n\n\nIf you want the date field to be visible, but not editable by the user, then set \nread_only=True\n and additionally set a \ndefault=...\n argument.\n\n\npublished = serializers.DateTimeField(read_only=True, default=timezone.now)\n\n\n\nThe field will not be writable to the user, but the default value will still be passed through to the \nvalidated_data\n.\n\n\nUsing with a hidden date field.\n\n\nIf you want the date field to be entirely hidden from the user, then use \nHiddenField\n. This field type does not accept user input, but instead always returns it's default value to the \nvalidated_data\n in the serializer.\n\n\npublished = serializers.HiddenField(default=timezone.now)\n\n\n\n\n\nNote\n: The \nUniqueFor\nRange\nValidation\n classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nAdvanced 'default' argument usage\n\n\nValidators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that \nis\n available as input to the validator.\n\n\nTwo patterns that you may want to use for this sort of validation include:\n\n\n\n\nUsing \nHiddenField\n. This field will be present in \nvalidated_data\n but \nwill not\n be used in the serializer output representation.\n\n\nUsing a standard field with \nread_only=True\n, but that also includes a \ndefault=\u2026\n argument. This field \nwill\n be used in the serializer output representation, but cannot be set directly by the user.\n\n\n\n\nREST framework includes a couple of defaults that may be useful in this context.\n\n\nCurrentUserDefault\n\n\nA default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.\n\n\nowner = serializers.HiddenField(\n default=serializers.CurrentUserDefault()\n)\n\n\n\nCreateOnlyDefault\n\n\nA default class that can be used to \nonly set a default argument during create operations\n. During updates the field is omitted.\n\n\nIt takes a single argument, which is the default value or callable that should be used during create operations.\n\n\ncreated_at = serializers.DateTimeField(\n read_only=True,\n default=CreateOnlyDefault(timezone.now)\n)\n\n\n\n\n\nWriting custom validators\n\n\nYou can use any of Django's existing validators, or write your own custom validators.\n\n\nFunction based\n\n\nA validator may be any callable that raises a \nserializers.ValidationError\n on failure.\n\n\ndef even_number(value):\n if value % 2 != 0:\n raise serializers.ValidationError('This field must be an even number.')\n\n\n\nClass based\n\n\nTo write a class based validator, use the \n__call__\n method. Class based validators are useful as they allow you to parameterize and reuse behavior.\n\n\nclass MultipleOf(object):\n def __init__(self, base):\n self.base = base\n\n def __call__(self, value):\n if value % self.base != 0:\n message = 'This field must be a multiple of %d.' % self.base\n raise serializers.ValidationError(message)\n\n\n\nUsing \nset_context()\n\n\nIn some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a \nset_context\n method on a class based validator.\n\n\ndef set_context(self, serializer_field):\n # Determine if this is an update or a create operation.\n # In `__call__` we can then use that information to modify the validation behavior.\n self.is_update = serializer_field.parent.instance is not None",
+ "text": "Validators\n\n\n\n\nValidators can be useful for re-using validation logic between different types of fields.\n\n\n \nDjango documentation\n\n\n\n\nMost of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.\n\n\nHowever, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.\n\n\nValidation in REST framework\n\n\nValidation in Django REST framework serializers is handled a little differently to how validation works in Django's \nModelForm\n class.\n\n\nWith \nModelForm\n the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:\n\n\n\n\nIt introduces a proper separation of concerns, making your code behavior more obvious.\n\n\nIt is easy to switch between using shortcut \nModelSerializer\n classes and using explicit \nSerializer\n classes. Any validation behavior being used for \nModelSerializer\n is simple to replicate.\n\n\nPrinting the \nrepr\n of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.\n\n\n\n\nWhen you're using \nModelSerializer\n all of this is handled automatically for you. If you want to drop down to using a \nSerializer\n classes instead, then you need to define the validation rules explicitly.\n\n\nExample\n\n\nAs an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.\n\n\nclass CustomerReportRecord(models.Model):\n time_raised = models.DateTimeField(default=timezone.now, editable=False)\n reference = models.CharField(unique=True, max_length=20)\n description = models.TextField()\n\n\n\nHere's a basic \nModelSerializer\n that we can use for creating or updating instances of \nCustomerReportRecord\n:\n\n\nclass CustomerReportSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomerReportRecord\n\n\n\nIf we open up the Django shell using \nmanage.py shell\n we can now\n\n\n from project.example.serializers import CustomerReportSerializer\n\n serializer = CustomerReportSerializer()\n\n print(repr(serializer))\nCustomerReportSerializer():\n id = IntegerField(label='ID', read_only=True)\n time_raised = DateTimeField(read_only=True)\n reference = CharField(max_length=20, validators=[\nUniqueValidator(queryset=CustomerReportRecord.objects.all())\n])\n description = CharField(style={'type': 'textarea'})\n\n\n\nThe interesting bit here is the \nreference\n field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.\n\n\nBecause of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.\n\n\n\n\nUniqueValidator\n\n\nThis validator can be used to enforce the \nunique=True\n constraint on model fields.\nIt takes a single required argument, and an optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThis validator should be applied to \nserializer fields\n, like so:\n\n\nslug = SlugField(\n max_length=100,\n validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)\n\n\n\nUniqueTogetherValidator\n\n\nThis validator can be used to enforce \nunique_together\n constraints on model instances.\nIt has two required arguments, and a single optional \nmessages\n argument:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfields\n \nrequired\n - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # ToDo items belong to a parent list, and have an ordering defined\n #\u00a0by the 'position' field. No two items in a given list may share\n # the same position.\n validators = [\n UniqueTogetherValidator(\n queryset=ToDoItem.objects.all(),\n fields=('list', 'position')\n )\n ]\n\n\n\n\n\nNote\n: The \nUniqueTogetherValidation\n class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nUniqueForDateValidator\n\n\nUniqueForMonthValidator\n\n\nUniqueForYearValidator\n\n\nThese validators can be used to enforce the \nunique_for_date\n, \nunique_for_month\n and \nunique_for_year\n constraints on model instances. They take the following arguments:\n\n\n\n\nqueryset\n \nrequired\n - This is the queryset against which uniqueness should be enforced.\n\n\nfield\n \nrequired\n - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.\n\n\ndate_field\n \nrequired\n - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.\n\n\nmessage\n - The error message that should be used when validation fails.\n\n\n\n\nThe validator should be applied to \nserializer classes\n, like so:\n\n\nclass ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # Blog posts should have a slug that is unique for the current year.\n validators = [\n UniqueForYearValidator(\n queryset=BlogPostItem.objects.all(),\n field='slug',\n date_field='published'\n )\n ]\n\n\n\nThe date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class \ndefault=...\n, because the value being used for the default wouldn't be generated until after the validation has run.\n\n\nThere are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using \nModelSerializer\n you'll probably simply rely on the defaults that REST framework generates for you, but if you are using \nSerializer\n or simply want more explicit control, use on of the styles demonstrated below.\n\n\nUsing with a writable date field.\n\n\nIf you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a \ndefault\n argument, or by setting \nrequired=True\n.\n\n\npublished = serializers.DateTimeField(required=True)\n\n\n\nUsing with a read-only date field.\n\n\nIf you want the date field to be visible, but not editable by the user, then set \nread_only=True\n and additionally set a \ndefault=...\n argument.\n\n\npublished = serializers.DateTimeField(read_only=True, default=timezone.now)\n\n\n\nThe field will not be writable to the user, but the default value will still be passed through to the \nvalidated_data\n.\n\n\nUsing with a hidden date field.\n\n\nIf you want the date field to be entirely hidden from the user, then use \nHiddenField\n. This field type does not accept user input, but instead always returns it's default value to the \nvalidated_data\n in the serializer.\n\n\npublished = serializers.HiddenField(default=timezone.now)\n\n\n\n\n\nNote\n: The \nUniqueFor\nRange\nValidation\n classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with \ndefault\n values are an exception to this as they always supply a value even when omitted from user input.\n\n\n\n\nAdvanced field defaults\n\n\nValidators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that \nis\n available as input to the validator.\n\n\nTwo patterns that you may want to use for this sort of validation include:\n\n\n\n\nUsing \nHiddenField\n. This field will be present in \nvalidated_data\n but \nwill not\n be used in the serializer output representation.\n\n\nUsing a standard field with \nread_only=True\n, but that also includes a \ndefault=\u2026\n argument. This field \nwill\n be used in the serializer output representation, but cannot be set directly by the user.\n\n\n\n\nREST framework includes a couple of defaults that may be useful in this context.\n\n\nCurrentUserDefault\n\n\nA default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.\n\n\nowner = serializers.HiddenField(\n default=serializers.CurrentUserDefault()\n)\n\n\n\nCreateOnlyDefault\n\n\nA default class that can be used to \nonly set a default argument during create operations\n. During updates the field is omitted.\n\n\nIt takes a single argument, which is the default value or callable that should be used during create operations.\n\n\ncreated_at = serializers.DateTimeField(\n read_only=True,\n default=CreateOnlyDefault(timezone.now)\n)\n\n\n\n\n\nLimitations of validators\n\n\nThere are some ambiguous cases where you'll need to instead handle validation\nexplicitly, rather than relying on the default serializer classes that\n\nModelSerializer\n generates.\n\n\nIn these cases you may want to disable the automatically generated validators,\nby specifying an empty list for the serializer \nMeta.validators\n attribute.\n\n\nOptional fields\n\n\nBy default \"unique together\" validation enforces that all fields be\n\nrequired=True\n. In some cases, you might want to explicit apply\n\nrequired=False\n to one of the fields, in which case the desired behaviour\nof the validation is ambiguous.\n\n\nIn this case you will typically need to exclude the validator from the\nserializer class, and instead write any validation logic explicitly, either\nin the \n.validate()\n method, or else in the view.\n\n\nFor example:\n\n\nclass BillingRecordSerializer(serializers.ModelSerializer):\n def validate(self, data):\n # Apply custom validation either here, or in the view.\n\n class Meta:\n fields = ('client', 'date', 'amount')\n extra_kwargs = {'client' {'required': 'False'}}\n validators = [] # Remove a default \"unique together\" constraint.\n\n\n\nUpdating nested serializers\n\n\nWhen applying an update to an existing instance, uniqueness validators will\nexclude the current instance from the uniqueness check. The current instance\nis available in the context of the uniqueness check, because it exists as\nan attribute on the serializer, having initially been passed using\n\ninstance=...\n when instantiating the serializer.\n\n\nIn the case of update operations on \nnested\n serializers there's no way of\napplying this exclusion, because the instance is not available.\n\n\nAgain, you'll probably want to explicitly remove the validator from the\nserializer class, and write the code the for the validation constraint\nexplicitly, in a \n.validate()\n method, or in the view.\n\n\nDebugging complex cases\n\n\nIf you're not sure exactly what behavior a \nModelSerializer\n class will\ngenerate it is usually a good idea to run \nmanage.py shell\n, and print\nan instance of the serializer, so that you can inspect the fields and\nvalidators that it automatically generates for you.\n\n\n serializer = MyComplexModelSerializer()\n\n print(serializer)\nclass MyComplexModelSerializer:\n my_fields = ...\n\n\n\nAlso keep in mind that with complex cases it can often be better to explicitly\ndefine your serializer classes, rather than relying on the default\n\nModelSerializer\n behavior. This involves a little more code, but ensures\nthat the resulting behavior is more transparent.\n\n\n\n\nWriting custom validators\n\n\nYou can use any of Django's existing validators, or write your own custom validators.\n\n\nFunction based\n\n\nA validator may be any callable that raises a \nserializers.ValidationError\n on failure.\n\n\ndef even_number(value):\n if value % 2 != 0:\n raise serializers.ValidationError('This field must be an even number.')\n\n\n\nClass based\n\n\nTo write a class based validator, use the \n__call__\n method. Class based validators are useful as they allow you to parameterize and reuse behavior.\n\n\nclass MultipleOf(object):\n def __init__(self, base):\n self.base = base\n\n def __call__(self, value):\n if value % self.base != 0:\n message = 'This field must be a multiple of %d.' % self.base\n raise serializers.ValidationError(message)\n\n\n\nUsing \nset_context()\n\n\nIn some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a \nset_context\n method on a class based validator.\n\n\ndef set_context(self, serializer_field):\n # Determine if this is an update or a create operation.\n # In `__call__` we can then use that information to modify the validation behavior.\n self.is_update = serializer_field.parent.instance is not None",
"title": "Validators"
},
{
@@ -1642,9 +2142,14 @@
},
{
"location": "/api-guide/validators/#validation-in-rest-framework",
- "text": "Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class. With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: It introduces a proper separation of concerns, making your code behavior more obvious. It is easy to switch between using shortcut ModelSerializer classes and using explicit Serializer classes. Any validation behavior being used for ModelSerializer is simple to replicate. Printing the repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance. When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using a Serializer classes instead, then you need to define the validation rules explicitly. Example As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint. class CustomerReportRecord(models.Model):\n time_raised = models.DateTimeField(default=timezone.now, editable=False)\n reference = models.CharField(unique=True, max_length=20)\n description = models.TextField() Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord : class CustomerReportSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomerReportRecord If we open up the Django shell using manage.py shell we can now from project.example.serializers import CustomerReportSerializer serializer = CustomerReportSerializer() print(repr(serializer))\nCustomerReportSerializer():\n id = IntegerField(label='ID', read_only=True)\n time_raised = DateTimeField(read_only=True)\n reference = CharField(max_length=20, validators=[ UniqueValidator(queryset=CustomerReportRecord.objects.all()) ])\n description = CharField(style={'type': 'textarea'}) The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field. Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.",
+ "text": "Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class. With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: It introduces a proper separation of concerns, making your code behavior more obvious. It is easy to switch between using shortcut ModelSerializer classes and using explicit Serializer classes. Any validation behavior being used for ModelSerializer is simple to replicate. Printing the repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance. When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using a Serializer classes instead, then you need to define the validation rules explicitly.",
"title": "Validation in REST framework"
},
+ {
+ "location": "/api-guide/validators/#example",
+ "text": "As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint. class CustomerReportRecord(models.Model):\n time_raised = models.DateTimeField(default=timezone.now, editable=False)\n reference = models.CharField(unique=True, max_length=20)\n description = models.TextField() Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord : class CustomerReportSerializer(serializers.ModelSerializer):\n class Meta:\n model = CustomerReportRecord If we open up the Django shell using manage.py shell we can now from project.example.serializers import CustomerReportSerializer serializer = CustomerReportSerializer() print(repr(serializer))\nCustomerReportSerializer():\n id = IntegerField(label='ID', read_only=True)\n time_raised = DateTimeField(read_only=True)\n reference = CharField(max_length=20, validators=[ UniqueValidator(queryset=CustomerReportRecord.objects.all()) ])\n description = CharField(style={'type': 'textarea'}) The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field. Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.",
+ "title": "Example"
+ },
{
"location": "/api-guide/validators/#uniquevalidator",
"text": "This validator can be used to enforce the unique=True constraint on model fields.\nIt takes a single required argument, and an optional messages argument: queryset required - This is the queryset against which uniqueness should be enforced. message - The error message that should be used when validation fails. This validator should be applied to serializer fields , like so: slug = SlugField(\n max_length=100,\n validators=[UniqueValidator(queryset=BlogPost.objects.all())]\n)",
@@ -1667,13 +2172,58 @@
},
{
"location": "/api-guide/validators/#uniqueforyearvalidator",
- "text": "These validators can be used to enforce the unique_for_date , unique_for_month and unique_for_year constraints on model instances. They take the following arguments: queryset required - This is the queryset against which uniqueness should be enforced. field required - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class. date_field required - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class. message - The error message that should be used when validation fails. The validator should be applied to serializer classes , like so: class ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # Blog posts should have a slug that is unique for the current year.\n validators = [\n UniqueForYearValidator(\n queryset=BlogPostItem.objects.all(),\n field='slug',\n date_field='published'\n )\n ] The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=... , because the value being used for the default wouldn't be generated until after the validation has run. There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below. Using with a writable date field. If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True . published = serializers.DateTimeField(required=True) Using with a read-only date field. If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument. published = serializers.DateTimeField(read_only=True, default=timezone.now) The field will not be writable to the user, but the default value will still be passed through to the validated_data . Using with a hidden date field. If you want the date field to be entirely hidden from the user, then use HiddenField . This field type does not accept user input, but instead always returns it's default value to the validated_data in the serializer. published = serializers.HiddenField(default=timezone.now) Note : The UniqueFor Range Validation classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.",
+ "text": "These validators can be used to enforce the unique_for_date , unique_for_month and unique_for_year constraints on model instances. They take the following arguments: queryset required - This is the queryset against which uniqueness should be enforced. field required - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class. date_field required - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class. message - The error message that should be used when validation fails. The validator should be applied to serializer classes , like so: class ExampleSerializer(serializers.Serializer):\n # ...\n class Meta:\n # Blog posts should have a slug that is unique for the current year.\n validators = [\n UniqueForYearValidator(\n queryset=BlogPostItem.objects.all(),\n field='slug',\n date_field='published'\n )\n ] The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=... , because the value being used for the default wouldn't be generated until after the validation has run. There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below.",
"title": "UniqueForYearValidator"
},
{
- "location": "/api-guide/validators/#advanced-default-argument-usage",
- "text": "Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator. Two patterns that you may want to use for this sort of validation include: Using HiddenField . This field will be present in validated_data but will not be used in the serializer output representation. Using a standard field with read_only=True , but that also includes a default=\u2026 argument. This field will be used in the serializer output representation, but cannot be set directly by the user. REST framework includes a couple of defaults that may be useful in this context. CurrentUserDefault A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer. owner = serializers.HiddenField(\n default=serializers.CurrentUserDefault()\n) CreateOnlyDefault A default class that can be used to only set a default argument during create operations . During updates the field is omitted. It takes a single argument, which is the default value or callable that should be used during create operations. created_at = serializers.DateTimeField(\n read_only=True,\n default=CreateOnlyDefault(timezone.now)\n)",
- "title": "Advanced 'default' argument usage"
+ "location": "/api-guide/validators/#using-with-a-writable-date-field",
+ "text": "If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True . published = serializers.DateTimeField(required=True)",
+ "title": "Using with a writable date field."
+ },
+ {
+ "location": "/api-guide/validators/#using-with-a-read-only-date-field",
+ "text": "If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument. published = serializers.DateTimeField(read_only=True, default=timezone.now) The field will not be writable to the user, but the default value will still be passed through to the validated_data .",
+ "title": "Using with a read-only date field."
+ },
+ {
+ "location": "/api-guide/validators/#using-with-a-hidden-date-field",
+ "text": "If you want the date field to be entirely hidden from the user, then use HiddenField . This field type does not accept user input, but instead always returns it's default value to the validated_data in the serializer. published = serializers.HiddenField(default=timezone.now) Note : The UniqueFor Range Validation classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.",
+ "title": "Using with a hidden date field."
+ },
+ {
+ "location": "/api-guide/validators/#advanced-field-defaults",
+ "text": "Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator. Two patterns that you may want to use for this sort of validation include: Using HiddenField . This field will be present in validated_data but will not be used in the serializer output representation. Using a standard field with read_only=True , but that also includes a default=\u2026 argument. This field will be used in the serializer output representation, but cannot be set directly by the user. REST framework includes a couple of defaults that may be useful in this context.",
+ "title": "Advanced field defaults"
+ },
+ {
+ "location": "/api-guide/validators/#currentuserdefault",
+ "text": "A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer. owner = serializers.HiddenField(\n default=serializers.CurrentUserDefault()\n)",
+ "title": "CurrentUserDefault"
+ },
+ {
+ "location": "/api-guide/validators/#createonlydefault",
+ "text": "A default class that can be used to only set a default argument during create operations . During updates the field is omitted. It takes a single argument, which is the default value or callable that should be used during create operations. created_at = serializers.DateTimeField(\n read_only=True,\n default=CreateOnlyDefault(timezone.now)\n)",
+ "title": "CreateOnlyDefault"
+ },
+ {
+ "location": "/api-guide/validators/#limitations-of-validators",
+ "text": "There are some ambiguous cases where you'll need to instead handle validation\nexplicitly, rather than relying on the default serializer classes that ModelSerializer generates. In these cases you may want to disable the automatically generated validators,\nby specifying an empty list for the serializer Meta.validators attribute.",
+ "title": "Limitations of validators"
+ },
+ {
+ "location": "/api-guide/validators/#optional-fields",
+ "text": "By default \"unique together\" validation enforces that all fields be required=True . In some cases, you might want to explicit apply required=False to one of the fields, in which case the desired behaviour\nof the validation is ambiguous. In this case you will typically need to exclude the validator from the\nserializer class, and instead write any validation logic explicitly, either\nin the .validate() method, or else in the view. For example: class BillingRecordSerializer(serializers.ModelSerializer):\n def validate(self, data):\n # Apply custom validation either here, or in the view.\n\n class Meta:\n fields = ('client', 'date', 'amount')\n extra_kwargs = {'client' {'required': 'False'}}\n validators = [] # Remove a default \"unique together\" constraint.",
+ "title": "Optional fields"
+ },
+ {
+ "location": "/api-guide/validators/#updating-nested-serializers",
+ "text": "When applying an update to an existing instance, uniqueness validators will\nexclude the current instance from the uniqueness check. The current instance\nis available in the context of the uniqueness check, because it exists as\nan attribute on the serializer, having initially been passed using instance=... when instantiating the serializer. In the case of update operations on nested serializers there's no way of\napplying this exclusion, because the instance is not available. Again, you'll probably want to explicitly remove the validator from the\nserializer class, and write the code the for the validation constraint\nexplicitly, in a .validate() method, or in the view.",
+ "title": "Updating nested serializers"
+ },
+ {
+ "location": "/api-guide/validators/#debugging-complex-cases",
+ "text": "If you're not sure exactly what behavior a ModelSerializer class will\ngenerate it is usually a good idea to run manage.py shell , and print\nan instance of the serializer, so that you can inspect the fields and\nvalidators that it automatically generates for you. serializer = MyComplexModelSerializer() print(serializer)\nclass MyComplexModelSerializer:\n my_fields = ... Also keep in mind that with complex cases it can often be better to explicitly\ndefine your serializer classes, rather than relying on the default ModelSerializer behavior. This involves a little more code, but ensures\nthat the resulting behavior is more transparent.",
+ "title": "Debugging complex cases"
},
{
"location": "/api-guide/validators/#writing-custom-validators",
@@ -1687,12 +2237,17 @@
},
{
"location": "/api-guide/validators/#class-based",
- "text": "To write a class based validator, use the __call__ method. Class based validators are useful as they allow you to parameterize and reuse behavior. class MultipleOf(object):\n def __init__(self, base):\n self.base = base\n\n def __call__(self, value):\n if value % self.base != 0:\n message = 'This field must be a multiple of %d.' % self.base\n raise serializers.ValidationError(message) Using set_context() In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a set_context method on a class based validator. def set_context(self, serializer_field):\n # Determine if this is an update or a create operation.\n # In `__call__` we can then use that information to modify the validation behavior.\n self.is_update = serializer_field.parent.instance is not None",
+ "text": "To write a class based validator, use the __call__ method. Class based validators are useful as they allow you to parameterize and reuse behavior. class MultipleOf(object):\n def __init__(self, base):\n self.base = base\n\n def __call__(self, value):\n if value % self.base != 0:\n message = 'This field must be a multiple of %d.' % self.base\n raise serializers.ValidationError(message)",
"title": "Class based"
},
+ {
+ "location": "/api-guide/validators/#using-set_context",
+ "text": "In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a set_context method on a class based validator. def set_context(self, serializer_field):\n # Determine if this is an update or a create operation.\n # In `__call__` we can then use that information to modify the validation behavior.\n self.is_update = serializer_field.parent.instance is not None",
+ "title": "Using set_context()"
+ },
{
"location": "/api-guide/authentication/",
- "text": "Authentication\n\n\n\n\nAuth needs to be pluggable.\n\n\n Jacob Kaplan-Moss, \n\"REST worst practices\"\n\n\n\n\nAuthentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The \npermission\n and \nthrottling\n policies can then use those credentials to determine if the request should be permitted.\n\n\nREST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.\n\n\nAuthentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.\n\n\nThe \nrequest.user\n property will typically be set to an instance of the \ncontrib.auth\n package's \nUser\n class.\n\n\nThe \nrequest.auth\n property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.\n\n\n\n\nNote:\n Don't forget that \nauthentication by itself won't allow or disallow an incoming request\n, it simply identifies the credentials that the request was made with.\n\n\nFor information on how to setup the permission polices for your API please see the \npermissions documentation\n.\n\n\n\n\nHow authentication is determined\n\n\nThe authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set \nrequest.user\n and \nrequest.auth\n using the return value of the first class that successfully authenticates.\n\n\nIf no class authenticates, \nrequest.user\n will be set to an instance of \ndjango.contrib.auth.models.AnonymousUser\n, and \nrequest.auth\n will be set to \nNone\n.\n\n\nThe value of \nrequest.user\n and \nrequest.auth\n for unauthenticated requests can be modified using the \nUNAUTHENTICATED_USER\n and \nUNAUTHENTICATED_TOKEN\n settings.\n\n\nSetting the authentication scheme\n\n\nThe default authentication schemes may be set globally, using the \nDEFAULT_AUTHENTICATION_CLASSES\n setting. For example.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n )\n}\n\n\n\nYou can also set the authentication scheme on a per-view or per-viewset basis,\nusing the \nAPIView\n class based views.\n\n\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n authentication_classes = (SessionAuthentication, BasicAuthentication)\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\n@api_view(['GET'])\n@authentication_classes((SessionAuthentication, BasicAuthentication))\n@permission_classes((IsAuthenticated,))\ndef example_view(request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nUnauthorized and Forbidden responses\n\n\nWhen an unauthenticated request is denied permission there are two different error codes that may be appropriate.\n\n\n\n\nHTTP 401 Unauthorized\n\n\nHTTP 403 Permission Denied\n\n\n\n\nHTTP 401 responses must always include a \nWWW-Authenticate\n header, that instructs the client how to authenticate. HTTP 403 responses do not include the \nWWW-Authenticate\n header.\n\n\nThe kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. \nThe first authentication class set on the view is used when determining the type of response\n.\n\n\nNote that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a \n403 Permission Denied\n response will always be used, regardless of the authentication scheme.\n\n\nApache mod_wsgi specific configuration\n\n\nNote that if deploying to \nApache using mod_wsgi\n, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.\n\n\nIf you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the \nWSGIPassAuthorization\n directive in the appropriate context and setting it to \n'On'\n.\n\n\n# this can go in either server config, virtual host, directory or .htaccess\nWSGIPassAuthorization On\n\n\n\n\n\nAPI Reference\n\n\nBasicAuthentication\n\n\nThis authentication scheme uses \nHTTP Basic Authentication\n, signed against a user's username and password. Basic authentication is generally only appropriate for testing.\n\n\nIf successfully authenticated, \nBasicAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Basic realm=\"api\"\n\n\n\nNote:\n If you use \nBasicAuthentication\n in production you must ensure that your API is only available over \nhttps\n. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.\n\n\nTokenAuthentication\n\n\nThis authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.\n\n\nTo use the \nTokenAuthentication\n scheme you'll need to \nconfigure the authentication classes\n to include \nTokenAuthentication\n, and additionally include \nrest_framework.authtoken\n in your \nINSTALLED_APPS\n setting:\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework.authtoken'\n)\n\n\n\n\n\nNote:\n Make sure to run \nmanage.py migrate\n after changing your settings. The \nrest_framework.authtoken\n app provides Django database migrations.\n\n\n\n\nYou'll also need to create tokens for your users.\n\n\nfrom rest_framework.authtoken.models import Token\n\ntoken = Token.objects.create(user=...)\nprint token.key\n\n\n\nFor clients to authenticate, the token key should be included in the \nAuthorization\n HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example:\n\n\nAuthorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\n\n\n\nNote:\n If you want to use a different keyword in the header, such as \nBearer\n, simply subclass \nTokenAuthentication\n and set the \nkeyword\n class variable.\n\n\nIf successfully authenticated, \nTokenAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be a \nrest_framework.authtoken.models.BasicToken\n instance.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Token\n\n\n\nThe \ncurl\n command line tool may be useful for testing token authenticated APIs. For example:\n\n\ncurl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'\n\n\n\n\n\nNote:\n If you use \nTokenAuthentication\n in production you must ensure that your API is only available over \nhttps\n.\n\n\n\n\nGenerating Tokens\n\n\nBy using signals\n\n\nIf you want every user to have an automatically generated Token, you can simply catch the User's \npost_save\n signal.\n\n\nfrom django.conf import settings\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n\n\nNote that you'll want to ensure you place this code snippet in an installed \nmodels.py\n module, or some other location that will be imported by Django on startup.\n\n\nIf you've already created some users, you can generate tokens for all existing users like this:\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user)\n\n\n\nBy exposing an api endpoint\n\n\nWhen using \nTokenAuthentication\n, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the \nobtain_auth_token\n view to your URLconf:\n\n\nfrom rest_framework.authtoken import views\nurlpatterns += [\n url(r'^api-token-auth/', views.obtain_auth_token)\n]\n\n\n\nNote that the URL part of the pattern can be whatever you want to use.\n\n\nThe \nobtain_auth_token\n view will return a JSON response when valid \nusername\n and \npassword\n fields are POSTed to the view using form data or JSON:\n\n\n{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }\n\n\n\nNote that the default \nobtain_auth_token\n view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the \nobtain_auth_token\n view, you can do so by overriding the \nObtainAuthToken\n view class, and using that in your url conf instead.\n\n\nWith Django admin\n\n\nIt is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the \nTokenAdmin\n class to customize it to your needs, more specifically by declaring the \nuser\n field as \nraw_field\n.\n\n\nyour_app/admin.py\n:\n\n\nfrom rest_framework.authtoken.admin import TokenAdmin\n\nTokenAdmin.raw_id_fields = ('user',)\n\n\n\nSessionAuthentication\n\n\nThis authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.\n\n\nIf successfully authenticated, \nSessionAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 403 Forbidden\n response.\n\n\nIf you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any \"unsafe\" HTTP method calls, such as \nPUT\n, \nPATCH\n, \nPOST\n or \nDELETE\n requests. See the \nDjango CSRF documentation\n for more details.\n\n\nWarning\n: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.\n\n\nCSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.\n\n\nCustom authentication\n\n\nTo implement a custom authentication scheme, subclass \nBaseAuthentication\n and override the \n.authenticate(self, request)\n method. The method should return a two-tuple of \n(user, auth)\n if authentication succeeds, or \nNone\n otherwise.\n\n\nIn some circumstances instead of returning \nNone\n, you may want to raise an \nAuthenticationFailed\n exception from the \n.authenticate()\n method.\n\n\nTypically the approach you should take is:\n\n\n\n\nIf authentication is not attempted, return \nNone\n. Any other authentication schemes also in use will still be checked.\n\n\nIf authentication is attempted but fails, raise a \nAuthenticationFailed\n exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.\n\n\n\n\nYou \nmay\n also override the \n.authenticate_header(self, request)\n method. If implemented, it should return a string that will be used as the value of the \nWWW-Authenticate\n header in a \nHTTP 401 Unauthorized\n response.\n\n\nIf the \n.authenticate_header()\n method is not overridden, the authentication scheme will return \nHTTP 403 Forbidden\n responses when an unauthenticated request is denied access.\n\n\nExample\n\n\nThe following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\n\nclass ExampleAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n username = request.META.get('X_USERNAME')\n if not username:\n return None\n\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n raise exceptions.AuthenticationFailed('No such user')\n\n return (user, None)\n\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango OAuth Toolkit\n\n\nThe \nDjango OAuth Toolkit\n package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by \nEvonove\n and uses the excellent \nOAuthLib\n. The package is well documented, and well supported and is currently our \nrecommended package for OAuth 2.0 support\n.\n\n\nInstallation \n configuration\n\n\nInstall using \npip\n.\n\n\npip install django-oauth-toolkit\n\n\n\nAdd the package to your \nINSTALLED_APPS\n and modify your REST framework settings.\n\n\nINSTALLED_APPS = (\n ...\n 'oauth2_provider',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.ext.rest_framework.OAuth2Authentication',\n )\n}\n\n\n\nFor more details see the \nDjango REST framework - Getting started\n documentation.\n\n\nDjango REST framework OAuth\n\n\nThe \nDjango REST framework OAuth\n package provides both OAuth1 and OAuth2 support for REST framework.\n\n\nThis package was previously included directly in REST framework but is now supported and maintained as a third party package.\n\n\nInstallation \n configuration\n\n\nInstall the package using \npip\n.\n\n\npip install djangorestframework-oauth\n\n\n\nFor details on configuration and usage see the Django REST framework OAuth documentation for \nauthentication\n and \npermissions\n.\n\n\nDigest Authentication\n\n\nHTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. \nJuan Riaza\n maintains the \ndjangorestframework-digestauth\n package which provides HTTP digest authentication support for REST framework.\n\n\nDjango OAuth2 Consumer\n\n\nThe \nDjango OAuth2 Consumer\n library from \nRediker Software\n is another package that provides \nOAuth 2.0 support for REST framework\n. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.\n\n\nJSON Web Token Authentication\n\n\nJSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. \nBlimp\n maintains the \ndjangorestframework-jwt\n package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.\n\n\nHawk HTTP Authentication\n\n\nThe \nHawkREST\n library builds on the \nMohawk\n library to let you work with \nHawk\n signed requests and responses in your API. \nHawk\n lets two parties securely communicate with each other using messages signed by a shared key. It is based on \nHTTP MAC access authentication\n (which was based on parts of \nOAuth 1.0\n).\n\n\nHTTP Signature Authentication\n\n\nHTTP Signature (currently a \nIETF draft\n) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to \nAmazon's HTTP Signature scheme\n, used by many of its services, it permits stateless, per-request authentication. \nElvio Toccalino\n maintains the \ndjangorestframework-httpsignature\n package which provides an easy to use HTTP Signature Authentication mechanism.\n\n\nDjoser\n\n\nDjoser\n library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.\n\n\ndjango-rest-auth\n\n\nDjango-rest-auth\n library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.\n\n\ndjango-rest-framework-social-oauth2\n\n\nDjango-rest-framework-social-oauth2\n library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to \"in-house\" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.\n\n\ndjango-rest-knox\n\n\nDjango-rest-knox\n library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).",
+ "text": "Authentication\n\n\n\n\nAuth needs to be pluggable.\n\n\n Jacob Kaplan-Moss, \n\"REST worst practices\"\n\n\n\n\nAuthentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The \npermission\n and \nthrottling\n policies can then use those credentials to determine if the request should be permitted.\n\n\nREST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.\n\n\nAuthentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.\n\n\nThe \nrequest.user\n property will typically be set to an instance of the \ncontrib.auth\n package's \nUser\n class.\n\n\nThe \nrequest.auth\n property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.\n\n\n\n\nNote:\n Don't forget that \nauthentication by itself won't allow or disallow an incoming request\n, it simply identifies the credentials that the request was made with.\n\n\nFor information on how to setup the permission polices for your API please see the \npermissions documentation\n.\n\n\n\n\nHow authentication is determined\n\n\nThe authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set \nrequest.user\n and \nrequest.auth\n using the return value of the first class that successfully authenticates.\n\n\nIf no class authenticates, \nrequest.user\n will be set to an instance of \ndjango.contrib.auth.models.AnonymousUser\n, and \nrequest.auth\n will be set to \nNone\n.\n\n\nThe value of \nrequest.user\n and \nrequest.auth\n for unauthenticated requests can be modified using the \nUNAUTHENTICATED_USER\n and \nUNAUTHENTICATED_TOKEN\n settings.\n\n\nSetting the authentication scheme\n\n\nThe default authentication schemes may be set globally, using the \nDEFAULT_AUTHENTICATION_CLASSES\n setting. For example.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n )\n}\n\n\n\nYou can also set the authentication scheme on a per-view or per-viewset basis,\nusing the \nAPIView\n class based views.\n\n\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n authentication_classes = (SessionAuthentication, BasicAuthentication)\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nOr, if you're using the \n@api_view\n decorator with function based views.\n\n\n@api_view(['GET'])\n@authentication_classes((SessionAuthentication, BasicAuthentication))\n@permission_classes((IsAuthenticated,))\ndef example_view(request, format=None):\n content = {\n 'user': unicode(request.user), # `django.contrib.auth.User` instance.\n 'auth': unicode(request.auth), # None\n }\n return Response(content)\n\n\n\nUnauthorized and Forbidden responses\n\n\nWhen an unauthenticated request is denied permission there are two different error codes that may be appropriate.\n\n\n\n\nHTTP 401 Unauthorized\n\n\nHTTP 403 Permission Denied\n\n\n\n\nHTTP 401 responses must always include a \nWWW-Authenticate\n header, that instructs the client how to authenticate. HTTP 403 responses do not include the \nWWW-Authenticate\n header.\n\n\nThe kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. \nThe first authentication class set on the view is used when determining the type of response\n.\n\n\nNote that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a \n403 Permission Denied\n response will always be used, regardless of the authentication scheme.\n\n\nApache mod_wsgi specific configuration\n\n\nNote that if deploying to \nApache using mod_wsgi\n, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.\n\n\nIf you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the \nWSGIPassAuthorization\n directive in the appropriate context and setting it to \n'On'\n.\n\n\n# this can go in either server config, virtual host, directory or .htaccess\nWSGIPassAuthorization On\n\n\n\n\n\nAPI Reference\n\n\nBasicAuthentication\n\n\nThis authentication scheme uses \nHTTP Basic Authentication\n, signed against a user's username and password. Basic authentication is generally only appropriate for testing.\n\n\nIf successfully authenticated, \nBasicAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Basic realm=\"api\"\n\n\n\nNote:\n If you use \nBasicAuthentication\n in production you must ensure that your API is only available over \nhttps\n. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.\n\n\nTokenAuthentication\n\n\nThis authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.\n\n\nTo use the \nTokenAuthentication\n scheme you'll need to \nconfigure the authentication classes\n to include \nTokenAuthentication\n, and additionally include \nrest_framework.authtoken\n in your \nINSTALLED_APPS\n setting:\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework.authtoken'\n)\n\n\n\n\n\nNote:\n Make sure to run \nmanage.py migrate\n after changing your settings. The \nrest_framework.authtoken\n app provides Django database migrations.\n\n\n\n\nYou'll also need to create tokens for your users.\n\n\nfrom rest_framework.authtoken.models import Token\n\ntoken = Token.objects.create(user=...)\nprint token.key\n\n\n\nFor clients to authenticate, the token key should be included in the \nAuthorization\n HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example:\n\n\nAuthorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\n\n\n\nNote:\n If you want to use a different keyword in the header, such as \nBearer\n, simply subclass \nTokenAuthentication\n and set the \nkeyword\n class variable.\n\n\nIf successfully authenticated, \nTokenAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be a \nrest_framework.authtoken.models.BasicToken\n instance.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 401 Unauthorized\n response with an appropriate WWW-Authenticate header. For example:\n\n\nWWW-Authenticate: Token\n\n\n\nThe \ncurl\n command line tool may be useful for testing token authenticated APIs. For example:\n\n\ncurl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'\n\n\n\n\n\nNote:\n If you use \nTokenAuthentication\n in production you must ensure that your API is only available over \nhttps\n.\n\n\n\n\nGenerating Tokens\n\n\nBy using signals\n\n\nIf you want every user to have an automatically generated Token, you can simply catch the User's \npost_save\n signal.\n\n\nfrom django.conf import settings\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance)\n\n\n\nNote that you'll want to ensure you place this code snippet in an installed \nmodels.py\n module, or some other location that will be imported by Django on startup.\n\n\nIf you've already created some users, you can generate tokens for all existing users like this:\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user)\n\n\n\nBy exposing an api endpoint\n\n\nWhen using \nTokenAuthentication\n, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the \nobtain_auth_token\n view to your URLconf:\n\n\nfrom rest_framework.authtoken import views\nurlpatterns += [\n url(r'^api-token-auth/', views.obtain_auth_token)\n]\n\n\n\nNote that the URL part of the pattern can be whatever you want to use.\n\n\nThe \nobtain_auth_token\n view will return a JSON response when valid \nusername\n and \npassword\n fields are POSTed to the view using form data or JSON:\n\n\n{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }\n\n\n\nNote that the default \nobtain_auth_token\n view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the \nobtain_auth_token\n view, you can do so by overriding the \nObtainAuthToken\n view class, and using that in your url conf instead.\n\n\nBy default there are no permissions or throttling applied to the \nobtain_auth_token\n view. If you do wish to apply throttling you'll need to override the view class,\nand include them using the \nthrottle_classes\n attribute.\n\n\nWith Django admin\n\n\nIt is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the \nTokenAdmin\n class to customize it to your needs, more specifically by declaring the \nuser\n field as \nraw_field\n.\n\n\nyour_app/admin.py\n:\n\n\nfrom rest_framework.authtoken.admin import TokenAdmin\n\nTokenAdmin.raw_id_fields = ('user',)\n\n\n\nSessionAuthentication\n\n\nThis authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.\n\n\nIf successfully authenticated, \nSessionAuthentication\n provides the following credentials.\n\n\n\n\nrequest.user\n will be a Django \nUser\n instance.\n\n\nrequest.auth\n will be \nNone\n.\n\n\n\n\nUnauthenticated responses that are denied permission will result in an \nHTTP 403 Forbidden\n response.\n\n\nIf you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any \"unsafe\" HTTP method calls, such as \nPUT\n, \nPATCH\n, \nPOST\n or \nDELETE\n requests. See the \nDjango CSRF documentation\n for more details.\n\n\nWarning\n: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.\n\n\nCSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.\n\n\nCustom authentication\n\n\nTo implement a custom authentication scheme, subclass \nBaseAuthentication\n and override the \n.authenticate(self, request)\n method. The method should return a two-tuple of \n(user, auth)\n if authentication succeeds, or \nNone\n otherwise.\n\n\nIn some circumstances instead of returning \nNone\n, you may want to raise an \nAuthenticationFailed\n exception from the \n.authenticate()\n method.\n\n\nTypically the approach you should take is:\n\n\n\n\nIf authentication is not attempted, return \nNone\n. Any other authentication schemes also in use will still be checked.\n\n\nIf authentication is attempted but fails, raise a \nAuthenticationFailed\n exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.\n\n\n\n\nYou \nmay\n also override the \n.authenticate_header(self, request)\n method. If implemented, it should return a string that will be used as the value of the \nWWW-Authenticate\n header in a \nHTTP 401 Unauthorized\n response.\n\n\nIf the \n.authenticate_header()\n method is not overridden, the authentication scheme will return \nHTTP 403 Forbidden\n responses when an unauthenticated request is denied access.\n\n\nExample\n\n\nThe following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.\n\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\n\nclass ExampleAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n username = request.META.get('X_USERNAME')\n if not username:\n return None\n\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n raise exceptions.AuthenticationFailed('No such user')\n\n return (user, None)\n\n\n\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDjango OAuth Toolkit\n\n\nThe \nDjango OAuth Toolkit\n package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by \nEvonove\n and uses the excellent \nOAuthLib\n. The package is well documented, and well supported and is currently our \nrecommended package for OAuth 2.0 support\n.\n\n\nInstallation \n configuration\n\n\nInstall using \npip\n.\n\n\npip install django-oauth-toolkit\n\n\n\nAdd the package to your \nINSTALLED_APPS\n and modify your REST framework settings.\n\n\nINSTALLED_APPS = (\n ...\n 'oauth2_provider',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.ext.rest_framework.OAuth2Authentication',\n )\n}\n\n\n\nFor more details see the \nDjango REST framework - Getting started\n documentation.\n\n\nDjango REST framework OAuth\n\n\nThe \nDjango REST framework OAuth\n package provides both OAuth1 and OAuth2 support for REST framework.\n\n\nThis package was previously included directly in REST framework but is now supported and maintained as a third party package.\n\n\nInstallation \n configuration\n\n\nInstall the package using \npip\n.\n\n\npip install djangorestframework-oauth\n\n\n\nFor details on configuration and usage see the Django REST framework OAuth documentation for \nauthentication\n and \npermissions\n.\n\n\nDigest Authentication\n\n\nHTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. \nJuan Riaza\n maintains the \ndjangorestframework-digestauth\n package which provides HTTP digest authentication support for REST framework.\n\n\nDjango OAuth2 Consumer\n\n\nThe \nDjango OAuth2 Consumer\n library from \nRediker Software\n is another package that provides \nOAuth 2.0 support for REST framework\n. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.\n\n\nJSON Web Token Authentication\n\n\nJSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. \nBlimp\n maintains the \ndjangorestframework-jwt\n package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.\n\n\nHawk HTTP Authentication\n\n\nThe \nHawkREST\n library builds on the \nMohawk\n library to let you work with \nHawk\n signed requests and responses in your API. \nHawk\n lets two parties securely communicate with each other using messages signed by a shared key. It is based on \nHTTP MAC access authentication\n (which was based on parts of \nOAuth 1.0\n).\n\n\nHTTP Signature Authentication\n\n\nHTTP Signature (currently a \nIETF draft\n) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to \nAmazon's HTTP Signature scheme\n, used by many of its services, it permits stateless, per-request authentication. \nElvio Toccalino\n maintains the \ndjangorestframework-httpsignature\n package which provides an easy to use HTTP Signature Authentication mechanism.\n\n\nDjoser\n\n\nDjoser\n library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.\n\n\ndjango-rest-auth\n\n\nDjango-rest-auth\n library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.\n\n\ndjango-rest-framework-social-oauth2\n\n\nDjango-rest-framework-social-oauth2\n library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to \"in-house\" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.\n\n\ndjango-rest-knox\n\n\nDjango-rest-knox\n library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).",
"title": "Authentication"
},
{
@@ -1732,9 +2287,29 @@
},
{
"location": "/api-guide/authentication/#tokenauthentication",
- "text": "This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication , and additionally include rest_framework.authtoken in your INSTALLED_APPS setting: INSTALLED_APPS = (\n ...\n 'rest_framework.authtoken'\n) Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations. You'll also need to create tokens for your users. from rest_framework.authtoken.models import Token\n\ntoken = Token.objects.create(user=...)\nprint token.key For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b Note: If you want to use a different keyword in the header, such as Bearer , simply subclass TokenAuthentication and set the keyword class variable. If successfully authenticated, TokenAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be a rest_framework.authtoken.models.BasicToken instance. Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Token The curl command line tool may be useful for testing token authenticated APIs. For example: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' Note: If you use TokenAuthentication in production you must ensure that your API is only available over https . Generating Tokens By using signals If you want every user to have an automatically generated Token, you can simply catch the User's post_save signal. from django.conf import settings\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance) Note that you'll want to ensure you place this code snippet in an installed models.py module, or some other location that will be imported by Django on startup. If you've already created some users, you can generate tokens for all existing users like this: from django.contrib.auth.models import User\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user) By exposing an api endpoint When using TokenAuthentication , you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the obtain_auth_token view to your URLconf: from rest_framework.authtoken import views\nurlpatterns += [\n url(r'^api-token-auth/', views.obtain_auth_token)\n] Note that the URL part of the pattern can be whatever you want to use. The obtain_auth_token view will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON: { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } Note that the default obtain_auth_token view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the obtain_auth_token view, you can do so by overriding the ObtainAuthToken view class, and using that in your url conf instead. With Django admin It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the TokenAdmin class to customize it to your needs, more specifically by declaring the user field as raw_field . your_app/admin.py : from rest_framework.authtoken.admin import TokenAdmin\n\nTokenAdmin.raw_id_fields = ('user',)",
+ "text": "This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication , and additionally include rest_framework.authtoken in your INSTALLED_APPS setting: INSTALLED_APPS = (\n ...\n 'rest_framework.authtoken'\n) Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations. You'll also need to create tokens for your users. from rest_framework.authtoken.models import Token\n\ntoken = Token.objects.create(user=...)\nprint token.key For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b Note: If you want to use a different keyword in the header, such as Bearer , simply subclass TokenAuthentication and set the keyword class variable. If successfully authenticated, TokenAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be a rest_framework.authtoken.models.BasicToken instance. Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Token The curl command line tool may be useful for testing token authenticated APIs. For example: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' Note: If you use TokenAuthentication in production you must ensure that your API is only available over https .",
"title": "TokenAuthentication"
},
+ {
+ "location": "/api-guide/authentication/#generating-tokens",
+ "text": "",
+ "title": "Generating Tokens"
+ },
+ {
+ "location": "/api-guide/authentication/#by-using-signals",
+ "text": "If you want every user to have an automatically generated Token, you can simply catch the User's post_save signal. from django.conf import settings\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom rest_framework.authtoken.models import Token\n\n@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef create_auth_token(sender, instance=None, created=False, **kwargs):\n if created:\n Token.objects.create(user=instance) Note that you'll want to ensure you place this code snippet in an installed models.py module, or some other location that will be imported by Django on startup. If you've already created some users, you can generate tokens for all existing users like this: from django.contrib.auth.models import User\nfrom rest_framework.authtoken.models import Token\n\nfor user in User.objects.all():\n Token.objects.get_or_create(user=user)",
+ "title": "By using signals"
+ },
+ {
+ "location": "/api-guide/authentication/#by-exposing-an-api-endpoint",
+ "text": "When using TokenAuthentication , you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the obtain_auth_token view to your URLconf: from rest_framework.authtoken import views\nurlpatterns += [\n url(r'^api-token-auth/', views.obtain_auth_token)\n] Note that the URL part of the pattern can be whatever you want to use. The obtain_auth_token view will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON: { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } Note that the default obtain_auth_token view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the obtain_auth_token view, you can do so by overriding the ObtainAuthToken view class, and using that in your url conf instead. By default there are no permissions or throttling applied to the obtain_auth_token view. If you do wish to apply throttling you'll need to override the view class,\nand include them using the throttle_classes attribute.",
+ "title": "By exposing an api endpoint"
+ },
+ {
+ "location": "/api-guide/authentication/#with-django-admin",
+ "text": "It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the TokenAdmin class to customize it to your needs, more specifically by declaring the user field as raw_field . your_app/admin.py : from rest_framework.authtoken.admin import TokenAdmin\n\nTokenAdmin.raw_id_fields = ('user',)",
+ "title": "With Django admin"
+ },
{
"location": "/api-guide/authentication/#sessionauthentication",
"text": "This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. If successfully authenticated, SessionAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be None . Unauthenticated responses that are denied permission will result in an HTTP 403 Forbidden response. If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any \"unsafe\" HTTP method calls, such as PUT , PATCH , POST or DELETE requests. See the Django CSRF documentation for more details. Warning : Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.",
@@ -1757,14 +2332,24 @@
},
{
"location": "/api-guide/authentication/#django-oauth-toolkit",
- "text": "The Django OAuth Toolkit package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by Evonove and uses the excellent OAuthLib . The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support . Installation configuration Install using pip . pip install django-oauth-toolkit Add the package to your INSTALLED_APPS and modify your REST framework settings. INSTALLED_APPS = (\n ...\n 'oauth2_provider',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.ext.rest_framework.OAuth2Authentication',\n )\n} For more details see the Django REST framework - Getting started documentation.",
+ "text": "The Django OAuth Toolkit package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by Evonove and uses the excellent OAuthLib . The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support .",
"title": "Django OAuth Toolkit"
},
+ {
+ "location": "/api-guide/authentication/#installation-configuration",
+ "text": "Install using pip . pip install django-oauth-toolkit Add the package to your INSTALLED_APPS and modify your REST framework settings. INSTALLED_APPS = (\n ...\n 'oauth2_provider',\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.ext.rest_framework.OAuth2Authentication',\n )\n} For more details see the Django REST framework - Getting started documentation.",
+ "title": "Installation & configuration"
+ },
{
"location": "/api-guide/authentication/#django-rest-framework-oauth",
- "text": "The Django REST framework OAuth package provides both OAuth1 and OAuth2 support for REST framework. This package was previously included directly in REST framework but is now supported and maintained as a third party package. Installation configuration Install the package using pip . pip install djangorestframework-oauth For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions .",
+ "text": "The Django REST framework OAuth package provides both OAuth1 and OAuth2 support for REST framework. This package was previously included directly in REST framework but is now supported and maintained as a third party package.",
"title": "Django REST framework OAuth"
},
+ {
+ "location": "/api-guide/authentication/#installation-configuration_1",
+ "text": "Install the package using pip . pip install djangorestframework-oauth For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions .",
+ "title": "Installation & configuration"
+ },
{
"location": "/api-guide/authentication/#digest-authentication",
"text": "HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. Juan Riaza maintains the djangorestframework-digestauth package which provides HTTP digest authentication support for REST framework.",
@@ -1827,9 +2412,14 @@
},
{
"location": "/api-guide/permissions/#object-level-permissions",
- "text": "REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. Object level permissions are run by REST framework's generic views when .get_object() is called.\nAs with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object. If you're writing your own views and want to enforce object level permissions,\nor if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object. This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions. For example: def get_object(self):\n obj = get_object_or_404(self.get_queryset())\n self.check_object_permissions(self.request, obj)\n return obj Limitations of object level permissions For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.",
+ "text": "REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. Object level permissions are run by REST framework's generic views when .get_object() is called.\nAs with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object. If you're writing your own views and want to enforce object level permissions,\nor if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object. This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions. For example: def get_object(self):\n obj = get_object_or_404(self.get_queryset())\n self.check_object_permissions(self.request, obj)\n return obj",
"title": "Object level permissions"
},
+ {
+ "location": "/api-guide/permissions/#limitations-of-object-level-permissions",
+ "text": "For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.",
+ "title": "Limitations of object level permissions"
+ },
{
"location": "/api-guide/permissions/#setting-the-permission-policy",
"text": "The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example. REST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.IsAuthenticated',\n )\n} If not specified, this setting defaults to allowing unrestricted access: 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.AllowAny',\n) You can also set the authentication policy on a per-view, or per-viewset basis,\nusing the APIView class based views. from rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nclass ExampleView(APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content) Or, if you're using the @api_view decorator with function based views. from rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\n@api_view('GET')\n@permission_classes((IsAuthenticated, ))\ndef example_view(request, format=None):\n content = {\n 'status': 'request was permitted'\n }\n return Response(content) Note: when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the settings.py file.",
@@ -1862,9 +2452,14 @@
},
{
"location": "/api-guide/permissions/#djangomodelpermissions",
- "text": "This permission class ties into Django's standard django.contrib.auth model permissions . This permission must only be applied to views that has a .queryset property set. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned. POST requests require the user to have the add permission on the model. PUT and PATCH requests require the user to have the change permission on the model. DELETE requests require the user to have the delete permission on the model. The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests. To use custom model permissions, override DjangoModelPermissions and set the .perms_map property. Refer to the source code for details. Using with views that do not include a queryset attribute. If you're using this permission with a view that uses an overridden get_queryset() method there may not be a queryset attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example: queryset = User.objects.none() # Required for DjangoModelPermissions",
+ "text": "This permission class ties into Django's standard django.contrib.auth model permissions . This permission must only be applied to views that has a .queryset property set. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned. POST requests require the user to have the add permission on the model. PUT and PATCH requests require the user to have the change permission on the model. DELETE requests require the user to have the delete permission on the model. The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests. To use custom model permissions, override DjangoModelPermissions and set the .perms_map property. Refer to the source code for details.",
"title": "DjangoModelPermissions"
},
+ {
+ "location": "/api-guide/permissions/#using-with-views-that-do-not-include-a-queryset-attribute",
+ "text": "If you're using this permission with a view that uses an overridden get_queryset() method there may not be a queryset attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example: queryset = User.objects.none() # Required for DjangoModelPermissions",
+ "title": "Using with views that do not include a queryset attribute."
+ },
{
"location": "/api-guide/permissions/#djangomodelpermissionsoranonreadonly",
"text": "Similar to DjangoModelPermissions , but also allows unauthenticated users to have read-only access to the API.",
@@ -1967,7 +2562,7 @@
},
{
"location": "/api-guide/filtering/",
- "text": "Filtering\n\n\n\n\nThe root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.\n\n\n \nDjango documentation\n\n\n\n\nThe default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.\n\n\nThe simplest way to filter the queryset of any view that subclasses \nGenericAPIView\n is to override the \n.get_queryset()\n method.\n\n\nOverriding this method allows you to customize the queryset returned by the view in a number of different ways.\n\n\nFiltering against the current user\n\n\nYou might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.\n\n\nYou can do so by filtering based on the value of \nrequest.user\n.\n\n\nFor example:\n\n\nfrom myapp.models import Purchase\nfrom myapp.serializers import PurchaseSerializer\nfrom rest_framework import generics\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases\n for the currently authenticated user.\n \"\"\"\n user = self.request.user\n return Purchase.objects.filter(purchaser=user)\n\n\n\nFiltering against the URL\n\n\nAnother style of filtering might involve restricting the queryset based on some part of the URL.\n\n\nFor example if your URL config contained an entry like this:\n\n\nurl('^purchases/(?P\nusername\n.+)/$', PurchaseList.as_view()),\n\n\n\nYou could then write a view that returned a purchase queryset filtered by the username portion of the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases for\n the user as determined by the username portion of the URL.\n \"\"\"\n username = self.kwargs['username']\n return Purchase.objects.filter(purchaser__username=username)\n\n\n\nFiltering against query parameters\n\n\nA final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.\n\n\nWe can override \n.get_queryset()\n to deal with URLs such as \nhttp://example.com/api/purchases?username=denvercoder9\n, and filter the queryset only if the \nusername\n parameter is included in the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n Optionally restricts the returned purchases to a given user,\n by filtering against a `username` query parameter in the URL.\n \"\"\"\n queryset = Purchase.objects.all()\n username = self.request.query_params.get('username', None)\n if username is not None:\n queryset = queryset.filter(purchaser__username=username)\n return queryset\n\n\n\n\n\nGeneric Filtering\n\n\nAs well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.\n\n\nGeneric filters can also present themselves as HTML controls in the browsable API and admin API.\n\n\n\n\nSetting filter backends\n\n\nThe default filter backends may be set globally, using the \nDEFAULT_FILTER_BACKENDS\n setting. For example.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)\n}\n\n\n\nYou can also set the filter backends on a per-view, or per-viewset basis,\nusing the \nGenericAPIView\n class based views.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer = UserSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n\n\n\nFiltering and object lookups\n\n\nNote that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.\n\n\nFor instance, given the previous example, and a product with an id of \n4675\n, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:\n\n\nhttp://example.com/api/products/4675/?category=clothing\nmax_price=10.00\n\n\n\nOverriding the initial queryset\n\n\nNote that you can use both an overridden \n.get_queryset()\n and generic filtering together, and everything will work as expected. For example, if \nProduct\n had a many-to-many relationship with \nUser\n, named \npurchase\n, you might want to write a view like this:\n\n\nclass PurchasedProductsList(generics.ListAPIView):\n \"\"\"\n Return a list of all the products that the authenticated\n user has ever purchased, with optional filtering.\n \"\"\"\n model = Product\n serializer_class = ProductSerializer\n filter_class = ProductFilter\n\n def get_queryset(self):\n user = self.request.user\n return user.purchase_set.all()\n\n\n\n\n\nAPI Guide\n\n\nDjangoFilterBackend\n\n\nThe \nDjangoFilterBackend\n class supports highly customizable field filtering, using the \ndjango-filter package\n.\n\n\nTo use REST framework's \nDjangoFilterBackend\n, first install \ndjango-filter\n.\n\n\npip install django-filter\n\n\n\nIf you are using the browsable API or admin API you may also want to install \ndjango-crispy-forms\n, which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML.\n\n\npip install django-crispy-forms\n\n\n\nWith crispy forms installed and added to Django's \nINSTALLED_APPS\n, the browsable API will present a filtering control for \nDjangoFilterBackend\n, like so:\n\n\n\n\nSpecifying filter fields\n\n\nIf all you need is simple equality-based filtering, you can set a \nfilter_fields\n attribute on the view, or viewset, listing the set of fields you wish to filter against.\n\n\nclass ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('category', 'in_stock')\n\n\n\nThis will automatically create a \nFilterSet\n class for the given fields, and will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nin_stock=True\n\n\n\nSpecifying a FilterSet\n\n\nFor more advanced filtering requirements you can specify a \nFilterSet\n class that should be used by the view. For example:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n min_price = django_filters.NumberFilter(name=\"price\", lookup_type='gte')\n max_price = django_filters.NumberFilter(name=\"price\", lookup_type='lte')\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'min_price', 'max_price']\n\nclass ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_class = ProductFilter\n\n\n\nWhich will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nmax_price=10.00\n\n\n\nYou can also span relationships using \ndjango-filter\n, let's assume that each\nproduct has foreign key to \nManufacturer\n model, so we create filter that\nfilters using \nManufacturer\n name. For example:\n\n\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer__name']\n\n\n\nThis enables us to make queries like:\n\n\nhttp://example.com/api/products?manufacturer__name=foo\n\n\n\nThis is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the \nFilterSet\n class:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n manufacturer = django_filters.CharFilter(name=\"manufacturer__name\")\n\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer']\n\n\n\nAnd now you can execute:\n\n\nhttp://example.com/api/products?manufacturer=foo\n\n\n\nFor more details on using filter sets see the \ndjango-filter documentation\n.\n\n\n\n\nHints \n Tips\n\n\n\n\nBy default filtering is not enabled. If you want to use \nDjangoFilterBackend\n remember to make sure it is installed by using the \n'DEFAULT_FILTER_BACKENDS'\n setting.\n\n\nWhen using boolean fields, you should use the values \nTrue\n and \nFalse\n in the URL query parameters, rather than \n0\n, \n1\n, \ntrue\n or \nfalse\n. (The allowed boolean values are currently hardwired in Django's \nNullBooleanSelect implementation\n.)\n\n\ndjango-filter\n supports filtering across relationships, using Django's double-underscore syntax.\n\n\nFor Django 1.3 support, make sure to install \ndjango-filter\n version 0.5.4, as later versions drop support for 1.3.\n\n\n\n\n\n\nSearchFilter\n\n\nThe \nSearchFilter\n class supports simple single query parameter based searching, and is based on the \nDjango admin's search functionality\n.\n\n\nWhen in use, the browsable API will include a \nSearchFilter\n control:\n\n\n\n\nThe \nSearchFilter\n class will only be applied if the view has a \nsearch_fields\n attribute set. The \nsearch_fields\n attribute should be a list of names of text type fields on the model, such as \nCharField\n or \nTextField\n.\n\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer = UserSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username', 'email')\n\n\n\nThis will allow the client to filter the items in the list by making queries such as:\n\n\nhttp://example.com/api/users?search=russell\n\n\n\nYou can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:\n\n\nsearch_fields = ('username', 'email', 'profile__profession')\n\n\n\nBy default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.\n\n\nThe search behavior may be restricted by prepending various characters to the \nsearch_fields\n.\n\n\n\n\n'^' Starts-with search.\n\n\n'=' Exact matches.\n\n\n'@' Full-text search. (Currently only supported Django's MySQL backend.)\n\n\n'$' Regex search.\n\n\n\n\nFor example:\n\n\nsearch_fields = ('=username', '=email')\n\n\n\nBy default, the search parameter is named \n'search\n', but this may be overridden with the \nSEARCH_PARAM\n setting.\n\n\nFor more details, see the \nDjango documentation\n.\n\n\n\n\nOrderingFilter\n\n\nThe \nOrderingFilter\n class supports simple query parameter controlled ordering of results.\n\n\n\n\nBy default, the query parameter is named \n'ordering'\n, but this may by overridden with the \nORDERING_PARAM\n setting.\n\n\nFor example, to order users by username:\n\n\nhttp://example.com/api/users?ordering=username\n\n\n\nThe client may also specify reverse orderings by prefixing the field name with '-', like so:\n\n\nhttp://example.com/api/users?ordering=-username\n\n\n\nMultiple orderings may also be specified:\n\n\nhttp://example.com/api/users?ordering=account,username\n\n\n\nSpecifying which fields may be ordered against\n\n\nIt's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an \nordering_fields\n attribute on the view, like so:\n\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email')\n\n\n\nThis helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.\n\n\nIf you \ndon't\n specify an \nordering_fields\n attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the \nserializer_class\n attribute.\n\n\nIf you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on \nany\n model field or queryset aggregate, by using the special value \n'__all__'\n.\n\n\nclass BookingsListView(generics.ListAPIView):\n queryset = Booking.objects.all()\n serializer_class = BookingSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = '__all__'\n\n\n\nSpecifying a default ordering\n\n\nIf an \nordering\n attribute is set on the view, this will be used as the default ordering.\n\n\nTypically you'd instead control this by setting \norder_by\n on the initial queryset, but using the \nordering\n parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.\n\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email')\n ordering = ('username',)\n\n\n\nThe \nordering\n attribute may be either a string or a list/tuple of strings.\n\n\n\n\nDjangoObjectPermissionsFilter\n\n\nThe \nDjangoObjectPermissionsFilter\n is intended to be used together with the \ndjango-guardian\n package, with custom \n'view'\n permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.\n\n\nIf you're using \nDjangoObjectPermissionsFilter\n, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass \nDjangoObjectPermissions\n and add \n'view'\n permissions to the \nperms_map\n attribute.\n\n\nA complete example using both \nDjangoObjectPermissionsFilter\n and \nDjangoObjectPermissions\n might look something like this.\n\n\npermissions.py\n:\n\n\nclass CustomObjectPermissions(permissions.DjangoObjectPermissions):\n \"\"\"\n Similar to `DjangoObjectPermissions`, but adding 'view' permissions.\n \"\"\"\n perms_map = {\n 'GET': ['%(app_label)s.view_%(model_name)s'],\n 'OPTIONS': ['%(app_label)s.view_%(model_name)s'],\n 'HEAD': ['%(app_label)s.view_%(model_name)s'],\n 'POST': ['%(app_label)s.add_%(model_name)s'],\n 'PUT': ['%(app_label)s.change_%(model_name)s'],\n 'PATCH': ['%(app_label)s.change_%(model_name)s'],\n 'DELETE': ['%(app_label)s.delete_%(model_name)s'],\n }\n\n\n\nviews.py\n:\n\n\nclass EventViewSet(viewsets.ModelViewSet):\n \"\"\"\n Viewset that only lists events if user has 'view' permissions, and only\n allows operations on individual events if user has appropriate 'view', 'add',\n 'change' or 'delete' permissions.\n \"\"\"\n queryset = Event.objects.all()\n serializer = EventSerializer\n filter_backends = (filters.DjangoObjectPermissionsFilter,)\n permission_classes = (myapp.permissions.CustomObjectPermissions,)\n\n\n\nFor more information on adding \n'view'\n permissions for models, see the \nrelevant section\n of the \ndjango-guardian\n documentation, and \nthis blogpost\n.\n\n\n\n\nCustom generic filtering\n\n\nYou can also provide your own generic filtering backend, or write an installable app for other developers to use.\n\n\nTo do so override \nBaseFilterBackend\n, and override the \n.filter_queryset(self, request, queryset, view)\n method. The method should return a new, filtered queryset.\n\n\nAs well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.\n\n\nExample\n\n\nFor example, you might need to restrict users to only being able to see objects they created.\n\n\nclass IsOwnerFilterBackend(filters.BaseFilterBackend):\n \"\"\"\n Filter that only allows users to see their own objects.\n \"\"\"\n def filter_queryset(self, request, queryset, view):\n return queryset.filter(owner=request.user)\n\n\n\nWe could achieve the same behavior by overriding \nget_queryset()\n on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.\n\n\nCustomizing the interface\n\n\nGeneric filters may also present an interface in the browsable API. To do so you should implement a \nto_html()\n method which returns a rendered HTML representation of the filter. This method should have the following signature:\n\n\nto_html(self, request, queryset, view)\n\n\nThe method should return a rendered HTML string.\n\n\nThird party packages\n\n\nThe following third party packages provide additional filter implementations.\n\n\nDjango REST framework filters package\n\n\nThe \ndjango-rest-framework-filters package\n works together with the \nDjangoFilterBackend\n class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.\n\n\nDjango REST framework full word search filter\n\n\nThe \ndjangorestframework-word-filter\n developed as alternative to \nfilters.SearchFilter\n which will search full word in text, or exact match.\n\n\nDjango URL Filter\n\n\ndjango-url-filter\n provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django \nQuerySet\ns.",
+ "text": "Filtering\n\n\n\n\nThe root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.\n\n\n \nDjango documentation\n\n\n\n\nThe default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.\n\n\nThe simplest way to filter the queryset of any view that subclasses \nGenericAPIView\n is to override the \n.get_queryset()\n method.\n\n\nOverriding this method allows you to customize the queryset returned by the view in a number of different ways.\n\n\nFiltering against the current user\n\n\nYou might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.\n\n\nYou can do so by filtering based on the value of \nrequest.user\n.\n\n\nFor example:\n\n\nfrom myapp.models import Purchase\nfrom myapp.serializers import PurchaseSerializer\nfrom rest_framework import generics\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases\n for the currently authenticated user.\n \"\"\"\n user = self.request.user\n return Purchase.objects.filter(purchaser=user)\n\n\n\nFiltering against the URL\n\n\nAnother style of filtering might involve restricting the queryset based on some part of the URL.\n\n\nFor example if your URL config contained an entry like this:\n\n\nurl('^purchases/(?P\nusername\n.+)/$', PurchaseList.as_view()),\n\n\n\nYou could then write a view that returned a purchase queryset filtered by the username portion of the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n This view should return a list of all the purchases for\n the user as determined by the username portion of the URL.\n \"\"\"\n username = self.kwargs['username']\n return Purchase.objects.filter(purchaser__username=username)\n\n\n\nFiltering against query parameters\n\n\nA final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.\n\n\nWe can override \n.get_queryset()\n to deal with URLs such as \nhttp://example.com/api/purchases?username=denvercoder9\n, and filter the queryset only if the \nusername\n parameter is included in the URL:\n\n\nclass PurchaseList(generics.ListAPIView):\n serializer_class = PurchaseSerializer\n\n def get_queryset(self):\n \"\"\"\n Optionally restricts the returned purchases to a given user,\n by filtering against a `username` query parameter in the URL.\n \"\"\"\n queryset = Purchase.objects.all()\n username = self.request.query_params.get('username', None)\n if username is not None:\n queryset = queryset.filter(purchaser__username=username)\n return queryset\n\n\n\n\n\nGeneric Filtering\n\n\nAs well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.\n\n\nGeneric filters can also present themselves as HTML controls in the browsable API and admin API.\n\n\n\n\nSetting filter backends\n\n\nThe default filter backends may be set globally, using the \nDEFAULT_FILTER_BACKENDS\n setting. For example.\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)\n}\n\n\n\nYou can also set the filter backends on a per-view, or per-viewset basis,\nusing the \nGenericAPIView\n class based views.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n\n\n\nFiltering and object lookups\n\n\nNote that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.\n\n\nFor instance, given the previous example, and a product with an id of \n4675\n, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:\n\n\nhttp://example.com/api/products/4675/?category=clothing\nmax_price=10.00\n\n\n\nOverriding the initial queryset\n\n\nNote that you can use both an overridden \n.get_queryset()\n and generic filtering together, and everything will work as expected. For example, if \nProduct\n had a many-to-many relationship with \nUser\n, named \npurchase\n, you might want to write a view like this:\n\n\nclass PurchasedProductsList(generics.ListAPIView):\n \"\"\"\n Return a list of all the products that the authenticated\n user has ever purchased, with optional filtering.\n \"\"\"\n model = Product\n serializer_class = ProductSerializer\n filter_class = ProductFilter\n\n def get_queryset(self):\n user = self.request.user\n return user.purchase_set.all()\n\n\n\n\n\nAPI Guide\n\n\nDjangoFilterBackend\n\n\nThe \nDjangoFilterBackend\n class supports highly customizable field filtering, using the \ndjango-filter package\n.\n\n\nTo use REST framework's \nDjangoFilterBackend\n, first install \ndjango-filter\n.\n\n\npip install django-filter\n\n\n\nIf you are using the browsable API or admin API you may also want to install \ndjango-crispy-forms\n, which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML.\n\n\npip install django-crispy-forms\n\n\n\nWith crispy forms installed and added to Django's \nINSTALLED_APPS\n, the browsable API will present a filtering control for \nDjangoFilterBackend\n, like so:\n\n\n\n\nSpecifying filter fields\n\n\nIf all you need is simple equality-based filtering, you can set a \nfilter_fields\n attribute on the view, or viewset, listing the set of fields you wish to filter against.\n\n\nclass ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('category', 'in_stock')\n\n\n\nThis will automatically create a \nFilterSet\n class for the given fields, and will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nin_stock=True\n\n\n\nSpecifying a FilterSet\n\n\nFor more advanced filtering requirements you can specify a \nFilterSet\n class that should be used by the view. For example:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n min_price = django_filters.NumberFilter(name=\"price\", lookup_type='gte')\n max_price = django_filters.NumberFilter(name=\"price\", lookup_type='lte')\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'min_price', 'max_price']\n\nclass ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_class = ProductFilter\n\n\n\nWhich will allow you to make requests such as:\n\n\nhttp://example.com/api/products?category=clothing\nmax_price=10.00\n\n\n\nYou can also span relationships using \ndjango-filter\n, let's assume that each\nproduct has foreign key to \nManufacturer\n model, so we create filter that\nfilters using \nManufacturer\n name. For example:\n\n\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer__name']\n\n\n\nThis enables us to make queries like:\n\n\nhttp://example.com/api/products?manufacturer__name=foo\n\n\n\nThis is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the \nFilterSet\n class:\n\n\nimport django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n manufacturer = django_filters.CharFilter(name=\"manufacturer__name\")\n\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer']\n\n\n\nAnd now you can execute:\n\n\nhttp://example.com/api/products?manufacturer=foo\n\n\n\nFor more details on using filter sets see the \ndjango-filter documentation\n.\n\n\n\n\nHints \n Tips\n\n\n\n\nBy default filtering is not enabled. If you want to use \nDjangoFilterBackend\n remember to make sure it is installed by using the \n'DEFAULT_FILTER_BACKENDS'\n setting.\n\n\nWhen using boolean fields, you should use the values \nTrue\n and \nFalse\n in the URL query parameters, rather than \n0\n, \n1\n, \ntrue\n or \nfalse\n. (The allowed boolean values are currently hardwired in Django's \nNullBooleanSelect implementation\n.)\n\n\ndjango-filter\n supports filtering across relationships, using Django's double-underscore syntax.\n\n\nFor Django 1.3 support, make sure to install \ndjango-filter\n version 0.5.4, as later versions drop support for 1.3.\n\n\n\n\n\n\nSearchFilter\n\n\nThe \nSearchFilter\n class supports simple single query parameter based searching, and is based on the \nDjango admin's search functionality\n.\n\n\nWhen in use, the browsable API will include a \nSearchFilter\n control:\n\n\n\n\nThe \nSearchFilter\n class will only be applied if the view has a \nsearch_fields\n attribute set. The \nsearch_fields\n attribute should be a list of names of text type fields on the model, such as \nCharField\n or \nTextField\n.\n\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username', 'email')\n\n\n\nThis will allow the client to filter the items in the list by making queries such as:\n\n\nhttp://example.com/api/users?search=russell\n\n\n\nYou can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:\n\n\nsearch_fields = ('username', 'email', 'profile__profession')\n\n\n\nBy default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.\n\n\nThe search behavior may be restricted by prepending various characters to the \nsearch_fields\n.\n\n\n\n\n'^' Starts-with search.\n\n\n'=' Exact matches.\n\n\n'@' Full-text search. (Currently only supported Django's MySQL backend.)\n\n\n'$' Regex search.\n\n\n\n\nFor example:\n\n\nsearch_fields = ('=username', '=email')\n\n\n\nBy default, the search parameter is named \n'search\n', but this may be overridden with the \nSEARCH_PARAM\n setting.\n\n\nFor more details, see the \nDjango documentation\n.\n\n\n\n\nOrderingFilter\n\n\nThe \nOrderingFilter\n class supports simple query parameter controlled ordering of results.\n\n\n\n\nBy default, the query parameter is named \n'ordering'\n, but this may by overridden with the \nORDERING_PARAM\n setting.\n\n\nFor example, to order users by username:\n\n\nhttp://example.com/api/users?ordering=username\n\n\n\nThe client may also specify reverse orderings by prefixing the field name with '-', like so:\n\n\nhttp://example.com/api/users?ordering=-username\n\n\n\nMultiple orderings may also be specified:\n\n\nhttp://example.com/api/users?ordering=account,username\n\n\n\nSpecifying which fields may be ordered against\n\n\nIt's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an \nordering_fields\n attribute on the view, like so:\n\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email')\n\n\n\nThis helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.\n\n\nIf you \ndon't\n specify an \nordering_fields\n attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the \nserializer_class\n attribute.\n\n\nIf you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on \nany\n model field or queryset aggregate, by using the special value \n'__all__'\n.\n\n\nclass BookingsListView(generics.ListAPIView):\n queryset = Booking.objects.all()\n serializer_class = BookingSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = '__all__'\n\n\n\nSpecifying a default ordering\n\n\nIf an \nordering\n attribute is set on the view, this will be used as the default ordering.\n\n\nTypically you'd instead control this by setting \norder_by\n on the initial queryset, but using the \nordering\n parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.\n\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email')\n ordering = ('username',)\n\n\n\nThe \nordering\n attribute may be either a string or a list/tuple of strings.\n\n\n\n\nDjangoObjectPermissionsFilter\n\n\nThe \nDjangoObjectPermissionsFilter\n is intended to be used together with the \ndjango-guardian\n package, with custom \n'view'\n permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.\n\n\nIf you're using \nDjangoObjectPermissionsFilter\n, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass \nDjangoObjectPermissions\n and add \n'view'\n permissions to the \nperms_map\n attribute.\n\n\nA complete example using both \nDjangoObjectPermissionsFilter\n and \nDjangoObjectPermissions\n might look something like this.\n\n\npermissions.py\n:\n\n\nclass CustomObjectPermissions(permissions.DjangoObjectPermissions):\n \"\"\"\n Similar to `DjangoObjectPermissions`, but adding 'view' permissions.\n \"\"\"\n perms_map = {\n 'GET': ['%(app_label)s.view_%(model_name)s'],\n 'OPTIONS': ['%(app_label)s.view_%(model_name)s'],\n 'HEAD': ['%(app_label)s.view_%(model_name)s'],\n 'POST': ['%(app_label)s.add_%(model_name)s'],\n 'PUT': ['%(app_label)s.change_%(model_name)s'],\n 'PATCH': ['%(app_label)s.change_%(model_name)s'],\n 'DELETE': ['%(app_label)s.delete_%(model_name)s'],\n }\n\n\n\nviews.py\n:\n\n\nclass EventViewSet(viewsets.ModelViewSet):\n \"\"\"\n Viewset that only lists events if user has 'view' permissions, and only\n allows operations on individual events if user has appropriate 'view', 'add',\n 'change' or 'delete' permissions.\n \"\"\"\n queryset = Event.objects.all()\n serializer_class = EventSerializer\n filter_backends = (filters.DjangoObjectPermissionsFilter,)\n permission_classes = (myapp.permissions.CustomObjectPermissions,)\n\n\n\nFor more information on adding \n'view'\n permissions for models, see the \nrelevant section\n of the \ndjango-guardian\n documentation, and \nthis blogpost\n.\n\n\n\n\nCustom generic filtering\n\n\nYou can also provide your own generic filtering backend, or write an installable app for other developers to use.\n\n\nTo do so override \nBaseFilterBackend\n, and override the \n.filter_queryset(self, request, queryset, view)\n method. The method should return a new, filtered queryset.\n\n\nAs well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.\n\n\nExample\n\n\nFor example, you might need to restrict users to only being able to see objects they created.\n\n\nclass IsOwnerFilterBackend(filters.BaseFilterBackend):\n \"\"\"\n Filter that only allows users to see their own objects.\n \"\"\"\n def filter_queryset(self, request, queryset, view):\n return queryset.filter(owner=request.user)\n\n\n\nWe could achieve the same behavior by overriding \nget_queryset()\n on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.\n\n\nCustomizing the interface\n\n\nGeneric filters may also present an interface in the browsable API. To do so you should implement a \nto_html()\n method which returns a rendered HTML representation of the filter. This method should have the following signature:\n\n\nto_html(self, request, queryset, view)\n\n\nThe method should return a rendered HTML string.\n\n\nThird party packages\n\n\nThe following third party packages provide additional filter implementations.\n\n\nDjango REST framework filters package\n\n\nThe \ndjango-rest-framework-filters package\n works together with the \nDjangoFilterBackend\n class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.\n\n\nDjango REST framework full word search filter\n\n\nThe \ndjangorestframework-word-filter\n developed as alternative to \nfilters.SearchFilter\n which will search full word in text, or exact match.\n\n\nDjango URL Filter\n\n\ndjango-url-filter\n provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django \nQuerySet\ns.",
"title": "Filtering"
},
{
@@ -1997,7 +2592,7 @@
},
{
"location": "/api-guide/filtering/#setting-filter-backends",
- "text": "The default filter backends may be set globally, using the DEFAULT_FILTER_BACKENDS setting. For example. REST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)\n} You can also set the filter backends on a per-view, or per-viewset basis,\nusing the GenericAPIView class based views. from django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer = UserSerializer\n filter_backends = (filters.DjangoFilterBackend,)",
+ "text": "The default filter backends may be set globally, using the DEFAULT_FILTER_BACKENDS setting. For example. REST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)\n} You can also set the filter backends on a per-view, or per-viewset basis,\nusing the GenericAPIView class based views. from django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.DjangoFilterBackend,)",
"title": "Setting filter backends"
},
{
@@ -2017,22 +2612,42 @@
},
{
"location": "/api-guide/filtering/#djangofilterbackend",
- "text": "The DjangoFilterBackend class supports highly customizable field filtering, using the django-filter package . To use REST framework's DjangoFilterBackend , first install django-filter . pip install django-filter If you are using the browsable API or admin API you may also want to install django-crispy-forms , which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML. pip install django-crispy-forms With crispy forms installed and added to Django's INSTALLED_APPS , the browsable API will present a filtering control for DjangoFilterBackend , like so: Specifying filter fields If all you need is simple equality-based filtering, you can set a filter_fields attribute on the view, or viewset, listing the set of fields you wish to filter against. class ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('category', 'in_stock') This will automatically create a FilterSet class for the given fields, and will allow you to make requests such as: http://example.com/api/products?category=clothing in_stock=True Specifying a FilterSet For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. For example: import django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n min_price = django_filters.NumberFilter(name=\"price\", lookup_type='gte')\n max_price = django_filters.NumberFilter(name=\"price\", lookup_type='lte')\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'min_price', 'max_price']\n\nclass ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_class = ProductFilter Which will allow you to make requests such as: http://example.com/api/products?category=clothing max_price=10.00 You can also span relationships using django-filter , let's assume that each\nproduct has foreign key to Manufacturer model, so we create filter that\nfilters using Manufacturer name. For example: from myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer__name'] This enables us to make queries like: http://example.com/api/products?manufacturer__name=foo This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the FilterSet class: import django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n manufacturer = django_filters.CharFilter(name=\"manufacturer__name\")\n\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer'] And now you can execute: http://example.com/api/products?manufacturer=foo For more details on using filter sets see the django-filter documentation . Hints Tips By default filtering is not enabled. If you want to use DjangoFilterBackend remember to make sure it is installed by using the 'DEFAULT_FILTER_BACKENDS' setting. When using boolean fields, you should use the values True and False in the URL query parameters, rather than 0 , 1 , true or false . (The allowed boolean values are currently hardwired in Django's NullBooleanSelect implementation .) django-filter supports filtering across relationships, using Django's double-underscore syntax. For Django 1.3 support, make sure to install django-filter version 0.5.4, as later versions drop support for 1.3.",
+ "text": "The DjangoFilterBackend class supports highly customizable field filtering, using the django-filter package . To use REST framework's DjangoFilterBackend , first install django-filter . pip install django-filter If you are using the browsable API or admin API you may also want to install django-crispy-forms , which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML. pip install django-crispy-forms With crispy forms installed and added to Django's INSTALLED_APPS , the browsable API will present a filtering control for DjangoFilterBackend , like so:",
"title": "DjangoFilterBackend"
},
+ {
+ "location": "/api-guide/filtering/#specifying-filter-fields",
+ "text": "If all you need is simple equality-based filtering, you can set a filter_fields attribute on the view, or viewset, listing the set of fields you wish to filter against. class ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('category', 'in_stock') This will automatically create a FilterSet class for the given fields, and will allow you to make requests such as: http://example.com/api/products?category=clothing in_stock=True",
+ "title": "Specifying filter fields"
+ },
+ {
+ "location": "/api-guide/filtering/#specifying-a-filterset",
+ "text": "For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. For example: import django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n min_price = django_filters.NumberFilter(name=\"price\", lookup_type='gte')\n max_price = django_filters.NumberFilter(name=\"price\", lookup_type='lte')\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'min_price', 'max_price']\n\nclass ProductList(generics.ListAPIView):\n queryset = Product.objects.all()\n serializer_class = ProductSerializer\n filter_backends = (filters.DjangoFilterBackend,)\n filter_class = ProductFilter Which will allow you to make requests such as: http://example.com/api/products?category=clothing max_price=10.00 You can also span relationships using django-filter , let's assume that each\nproduct has foreign key to Manufacturer model, so we create filter that\nfilters using Manufacturer name. For example: from myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer__name'] This enables us to make queries like: http://example.com/api/products?manufacturer__name=foo This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the FilterSet class: import django_filters\nfrom myapp.models import Product\nfrom myapp.serializers import ProductSerializer\nfrom rest_framework import filters\nfrom rest_framework import generics\n\nclass ProductFilter(filters.FilterSet):\n manufacturer = django_filters.CharFilter(name=\"manufacturer__name\")\n\n class Meta:\n model = Product\n fields = ['category', 'in_stock', 'manufacturer'] And now you can execute: http://example.com/api/products?manufacturer=foo For more details on using filter sets see the django-filter documentation . Hints Tips By default filtering is not enabled. If you want to use DjangoFilterBackend remember to make sure it is installed by using the 'DEFAULT_FILTER_BACKENDS' setting. When using boolean fields, you should use the values True and False in the URL query parameters, rather than 0 , 1 , true or false . (The allowed boolean values are currently hardwired in Django's NullBooleanSelect implementation .) django-filter supports filtering across relationships, using Django's double-underscore syntax. For Django 1.3 support, make sure to install django-filter version 0.5.4, as later versions drop support for 1.3.",
+ "title": "Specifying a FilterSet"
+ },
{
"location": "/api-guide/filtering/#searchfilter",
- "text": "The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality . When in use, the browsable API will include a SearchFilter control: The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField . class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer = UserSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username', 'email') This will allow the client to filter the items in the list by making queries such as: http://example.com/api/users?search=russell You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: search_fields = ('username', 'email', 'profile__profession') By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. The search behavior may be restricted by prepending various characters to the search_fields . '^' Starts-with search. '=' Exact matches. '@' Full-text search. (Currently only supported Django's MySQL backend.) '$' Regex search. For example: search_fields = ('=username', '=email') By default, the search parameter is named 'search ', but this may be overridden with the SEARCH_PARAM setting. For more details, see the Django documentation .",
+ "text": "The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality . When in use, the browsable API will include a SearchFilter control: The SearchFilter class will only be applied if the view has a search_fields attribute set. The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField . class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('username', 'email') This will allow the client to filter the items in the list by making queries such as: http://example.com/api/users?search=russell You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: search_fields = ('username', 'email', 'profile__profession') By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. The search behavior may be restricted by prepending various characters to the search_fields . '^' Starts-with search. '=' Exact matches. '@' Full-text search. (Currently only supported Django's MySQL backend.) '$' Regex search. For example: search_fields = ('=username', '=email') By default, the search parameter is named 'search ', but this may be overridden with the SEARCH_PARAM setting. For more details, see the Django documentation .",
"title": "SearchFilter"
},
{
"location": "/api-guide/filtering/#orderingfilter",
- "text": "The OrderingFilter class supports simple query parameter controlled ordering of results. By default, the query parameter is named 'ordering' , but this may by overridden with the ORDERING_PARAM setting. For example, to order users by username: http://example.com/api/users?ordering=username The client may also specify reverse orderings by prefixing the field name with '-', like so: http://example.com/api/users?ordering=-username Multiple orderings may also be specified: http://example.com/api/users?ordering=account,username Specifying which fields may be ordered against It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an ordering_fields attribute on the view, like so: class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email') This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data. If you don't specify an ordering_fields attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the serializer_class attribute. If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on any model field or queryset aggregate, by using the special value '__all__' . class BookingsListView(generics.ListAPIView):\n queryset = Booking.objects.all()\n serializer_class = BookingSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = '__all__' Specifying a default ordering If an ordering attribute is set on the view, this will be used as the default ordering. Typically you'd instead control this by setting order_by on the initial queryset, but using the ordering parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results. class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email')\n ordering = ('username',) The ordering attribute may be either a string or a list/tuple of strings.",
+ "text": "The OrderingFilter class supports simple query parameter controlled ordering of results. By default, the query parameter is named 'ordering' , but this may by overridden with the ORDERING_PARAM setting. For example, to order users by username: http://example.com/api/users?ordering=username The client may also specify reverse orderings by prefixing the field name with '-', like so: http://example.com/api/users?ordering=-username Multiple orderings may also be specified: http://example.com/api/users?ordering=account,username",
"title": "OrderingFilter"
},
+ {
+ "location": "/api-guide/filtering/#specifying-which-fields-may-be-ordered-against",
+ "text": "It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an ordering_fields attribute on the view, like so: class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email') This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data. If you don't specify an ordering_fields attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the serializer_class attribute. If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on any model field or queryset aggregate, by using the special value '__all__' . class BookingsListView(generics.ListAPIView):\n queryset = Booking.objects.all()\n serializer_class = BookingSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = '__all__'",
+ "title": "Specifying which fields may be ordered against"
+ },
+ {
+ "location": "/api-guide/filtering/#specifying-a-default-ordering",
+ "text": "If an ordering attribute is set on the view, this will be used as the default ordering. Typically you'd instead control this by setting order_by on the initial queryset, but using the ordering parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results. class UserListView(generics.ListAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n filter_backends = (filters.OrderingFilter,)\n ordering_fields = ('username', 'email')\n ordering = ('username',) The ordering attribute may be either a string or a list/tuple of strings.",
+ "title": "Specifying a default ordering"
+ },
{
"location": "/api-guide/filtering/#djangoobjectpermissionsfilter",
- "text": "The DjangoObjectPermissionsFilter is intended to be used together with the django-guardian package, with custom 'view' permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission. If you're using DjangoObjectPermissionsFilter , you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass DjangoObjectPermissions and add 'view' permissions to the perms_map attribute. A complete example using both DjangoObjectPermissionsFilter and DjangoObjectPermissions might look something like this. permissions.py : class CustomObjectPermissions(permissions.DjangoObjectPermissions):\n \"\"\"\n Similar to `DjangoObjectPermissions`, but adding 'view' permissions.\n \"\"\"\n perms_map = {\n 'GET': ['%(app_label)s.view_%(model_name)s'],\n 'OPTIONS': ['%(app_label)s.view_%(model_name)s'],\n 'HEAD': ['%(app_label)s.view_%(model_name)s'],\n 'POST': ['%(app_label)s.add_%(model_name)s'],\n 'PUT': ['%(app_label)s.change_%(model_name)s'],\n 'PATCH': ['%(app_label)s.change_%(model_name)s'],\n 'DELETE': ['%(app_label)s.delete_%(model_name)s'],\n } views.py : class EventViewSet(viewsets.ModelViewSet):\n \"\"\"\n Viewset that only lists events if user has 'view' permissions, and only\n allows operations on individual events if user has appropriate 'view', 'add',\n 'change' or 'delete' permissions.\n \"\"\"\n queryset = Event.objects.all()\n serializer = EventSerializer\n filter_backends = (filters.DjangoObjectPermissionsFilter,)\n permission_classes = (myapp.permissions.CustomObjectPermissions,) For more information on adding 'view' permissions for models, see the relevant section of the django-guardian documentation, and this blogpost .",
+ "text": "The DjangoObjectPermissionsFilter is intended to be used together with the django-guardian package, with custom 'view' permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission. If you're using DjangoObjectPermissionsFilter , you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass DjangoObjectPermissions and add 'view' permissions to the perms_map attribute. A complete example using both DjangoObjectPermissionsFilter and DjangoObjectPermissions might look something like this. permissions.py : class CustomObjectPermissions(permissions.DjangoObjectPermissions):\n \"\"\"\n Similar to `DjangoObjectPermissions`, but adding 'view' permissions.\n \"\"\"\n perms_map = {\n 'GET': ['%(app_label)s.view_%(model_name)s'],\n 'OPTIONS': ['%(app_label)s.view_%(model_name)s'],\n 'HEAD': ['%(app_label)s.view_%(model_name)s'],\n 'POST': ['%(app_label)s.add_%(model_name)s'],\n 'PUT': ['%(app_label)s.change_%(model_name)s'],\n 'PATCH': ['%(app_label)s.change_%(model_name)s'],\n 'DELETE': ['%(app_label)s.delete_%(model_name)s'],\n } views.py : class EventViewSet(viewsets.ModelViewSet):\n \"\"\"\n Viewset that only lists events if user has 'view' permissions, and only\n allows operations on individual events if user has appropriate 'view', 'add',\n 'change' or 'delete' permissions.\n \"\"\"\n queryset = Event.objects.all()\n serializer_class = EventSerializer\n filter_backends = (filters.DjangoObjectPermissionsFilter,)\n permission_classes = (myapp.permissions.CustomObjectPermissions,) For more information on adding 'view' permissions for models, see the relevant section of the django-guardian documentation, and this blogpost .",
"title": "DjangoObjectPermissionsFilter"
},
{
@@ -2097,19 +2712,54 @@
},
{
"location": "/api-guide/pagination/#pagenumberpagination",
- "text": "This pagination style accepts a single number page number in the request query parameters. Request : GET https://api.example.org/accounts/?page=4 Response : HTTP 200 OK\n{\n \"count\": 1023\n \"next\": \"https://api.example.org/accounts/?page=5\",\n \"previous\": \"https://api.example.org/accounts/?page=3\",\n \"results\": [\n \u2026\n ]\n} Setup To enable the PageNumberPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired: REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n} On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis. Configuration The PageNumberPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the PageNumberPagination class, and then enable your custom pagination class as above. django_paginator_class - The Django Paginator class to use. Default is django.core.paginator.Paginator , which should be fine for most use cases. page_size - A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. page_query_param - A string value indicating the name of the query parameter to use for the pagination control. page_size_query_param - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to None , indicating that the client may not control the requested page size. max_page_size - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if page_size_query_param is also set. last_page_strings - A list or tuple of string values indicating values that may be used with the page_query_param to request the final page in the set. Defaults to ('last',) template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" .",
+ "text": "This pagination style accepts a single number page number in the request query parameters. Request : GET https://api.example.org/accounts/?page=4 Response : HTTP 200 OK\n{\n \"count\": 1023\n \"next\": \"https://api.example.org/accounts/?page=5\",\n \"previous\": \"https://api.example.org/accounts/?page=3\",\n \"results\": [\n \u2026\n ]\n}",
"title": "PageNumberPagination"
},
+ {
+ "location": "/api-guide/pagination/#setup",
+ "text": "To enable the PageNumberPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired: REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 100\n} On GenericAPIView subclasses you may also set the pagination_class attribute to select PageNumberPagination on a per-view basis.",
+ "title": "Setup"
+ },
+ {
+ "location": "/api-guide/pagination/#configuration",
+ "text": "The PageNumberPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the PageNumberPagination class, and then enable your custom pagination class as above. django_paginator_class - The Django Paginator class to use. Default is django.core.paginator.Paginator , which should be fine for most use cases. page_size - A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. page_query_param - A string value indicating the name of the query parameter to use for the pagination control. page_size_query_param - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to None , indicating that the client may not control the requested page size. max_page_size - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if page_size_query_param is also set. last_page_strings - A list or tuple of string values indicating values that may be used with the page_query_param to request the final page in the set. Defaults to ('last',) template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" .",
+ "title": "Configuration"
+ },
{
"location": "/api-guide/pagination/#limitoffsetpagination",
- "text": "This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a \"limit\" and an \n\"offset\" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the page_size in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. Request : GET https://api.example.org/accounts/?limit=100 offset=400 Response : HTTP 200 OK\n{\n \"count\": 1023\n \"next\": \"https://api.example.org/accounts/?limit=100 offset=500\",\n \"previous\": \"https://api.example.org/accounts/?limit=100 offset=300\",\n \"results\": [\n \u2026\n ]\n} Setup To enable the LimitOffsetPagination style globally, use the following configuration: REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'\n} Optionally, you may also set a PAGE_SIZE key. If the PAGE_SIZE parameter is also used then the limit query parameter will be optional, and may be omitted by the client. On GenericAPIView subclasses you may also set the pagination_class attribute to select LimitOffsetPagination on a per-view basis. Configuration The LimitOffsetPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the LimitOffsetPagination class, and then enable your custom pagination class as above. default_limit - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the PAGE_SIZE settings key. limit_query_param - A string value indicating the name of the \"limit\" query parameter. Defaults to 'limit' . offset_query_param - A string value indicating the name of the \"offset\" query parameter. Defaults to 'offset' . max_limit - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to None . template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" .",
+ "text": "This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a \"limit\" and an \n\"offset\" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the page_size in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. Request : GET https://api.example.org/accounts/?limit=100 offset=400 Response : HTTP 200 OK\n{\n \"count\": 1023\n \"next\": \"https://api.example.org/accounts/?limit=100 offset=500\",\n \"previous\": \"https://api.example.org/accounts/?limit=100 offset=300\",\n \"results\": [\n \u2026\n ]\n}",
"title": "LimitOffsetPagination"
},
+ {
+ "location": "/api-guide/pagination/#setup_1",
+ "text": "To enable the LimitOffsetPagination style globally, use the following configuration: REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'\n} Optionally, you may also set a PAGE_SIZE key. If the PAGE_SIZE parameter is also used then the limit query parameter will be optional, and may be omitted by the client. On GenericAPIView subclasses you may also set the pagination_class attribute to select LimitOffsetPagination on a per-view basis.",
+ "title": "Setup"
+ },
+ {
+ "location": "/api-guide/pagination/#configuration_1",
+ "text": "The LimitOffsetPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the LimitOffsetPagination class, and then enable your custom pagination class as above. default_limit - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the PAGE_SIZE settings key. limit_query_param - A string value indicating the name of the \"limit\" query parameter. Defaults to 'limit' . offset_query_param - A string value indicating the name of the \"offset\" query parameter. Defaults to 'offset' . max_limit - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to None . template - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/numbers.html\" .",
+ "title": "Configuration"
+ },
{
"location": "/api-guide/pagination/#cursorpagination",
- "text": "The cursor-based pagination presents an opaque \"cursor\" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: Provides a consistent pagination view. When used properly CursorPagination ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases. Details and limitations Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by \"-created\" . This assumes that there must be a 'created' timestamp field on the model instances, and will present a \"timeline\" style paginated view, with the most recently added items first. You can modify the ordering by overriding the 'ordering' attribute on the pagination class, or by using the OrderingFilter filter class together with CursorPagination . When used with OrderingFilter you should strongly consider restricting the fields that the user may order by. Proper usage of cursor pagination should have an ordering field that satisfies the following: Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart \"position plus offset\" style that allows it to properly support not-strictly-unique values as the ordering. Should be a non-nullable value that can be coerced to a string. The field should have a database index. Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination. For more technical details on the implementation we use for cursor pagination, the \"Building cursors for the Disqus API\" blog post gives a good overview of the basic approach. Setup To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired: REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',\n 'PAGE_SIZE': 100\n} On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis. Configuration The CursorPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the CursorPagination class, and then enable your custom pagination class as above. page_size = A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. cursor_query_param = A string value indicating the name of the \"cursor\" query parameter. Defaults to 'cursor' . ordering = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: ordering = 'slug' . Defaults to -created . This value may also be overridden by using OrderingFilter on the view. template = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/previous_and_next.html\" .",
+ "text": "The cursor-based pagination presents an opaque \"cursor\" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: Provides a consistent pagination view. When used properly CursorPagination ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases.",
"title": "CursorPagination"
},
+ {
+ "location": "/api-guide/pagination/#details-and-limitations",
+ "text": "Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by \"-created\" . This assumes that there must be a 'created' timestamp field on the model instances, and will present a \"timeline\" style paginated view, with the most recently added items first. You can modify the ordering by overriding the 'ordering' attribute on the pagination class, or by using the OrderingFilter filter class together with CursorPagination . When used with OrderingFilter you should strongly consider restricting the fields that the user may order by. Proper usage of cursor pagination should have an ordering field that satisfies the following: Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart \"position plus offset\" style that allows it to properly support not-strictly-unique values as the ordering. Should be a non-nullable value that can be coerced to a string. The field should have a database index. Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination. For more technical details on the implementation we use for cursor pagination, the \"Building cursors for the Disqus API\" blog post gives a good overview of the basic approach.",
+ "title": "Details and limitations"
+ },
+ {
+ "location": "/api-guide/pagination/#setup_2",
+ "text": "To enable the CursorPagination style globally, use the following configuration, modifying the PAGE_SIZE as desired: REST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',\n 'PAGE_SIZE': 100\n} On GenericAPIView subclasses you may also set the pagination_class attribute to select CursorPagination on a per-view basis.",
+ "title": "Setup"
+ },
+ {
+ "location": "/api-guide/pagination/#configuration_2",
+ "text": "The CursorPagination class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the CursorPagination class, and then enable your custom pagination class as above. page_size = A numeric value indicating the page size. If set, this overrides the PAGE_SIZE setting. Defaults to the same value as the PAGE_SIZE settings key. cursor_query_param = A string value indicating the name of the \"cursor\" query parameter. Defaults to 'cursor' . ordering = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: ordering = 'slug' . Defaults to -created . This value may also be overridden by using OrderingFilter on the view. template = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to None to disable HTML pagination controls completely. Defaults to \"rest_framework/pagination/previous_and_next.html\" .",
+ "title": "Configuration"
+ },
{
"location": "/api-guide/pagination/#custom-pagination-styles",
"text": "To create a custom pagination serializer class you should subclass pagination.BasePagination and override the paginate_queryset(self, queryset, request, view=None) and get_paginated_response(self, data) methods: The paginate_queryset method is passed the initial queryset and should return an iterable object that contains only the data in the requested page. The get_paginated_response method is passed the serialized page data and should return a Response instance. Note that the paginate_queryset method may set state on the pagination instance, that may later be used by the get_paginated_response method.",
@@ -2137,9 +2787,14 @@
},
{
"location": "/api-guide/pagination/#customizing-the-controls",
- "text": "You can override the templates that render the HTML pagination controls. The two built-in styles are: rest_framework/pagination/numbers.html rest_framework/pagination/previous_and_next.html Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting template = None as an attribute on the class. You'll then need to configure your DEFAULT_PAGINATION_CLASS settings key to use your custom class as the default pagination style. Low-level API The low-level API for determining if a pagination class should display the controls or not is exposed as a display_page_controls attribute on the pagination instance. Custom pagination classes should be set to True in the paginate_queryset method if they require the HTML pagination controls to be displayed. The .to_html() and .get_html_context() methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.",
+ "text": "You can override the templates that render the HTML pagination controls. The two built-in styles are: rest_framework/pagination/numbers.html rest_framework/pagination/previous_and_next.html Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting template = None as an attribute on the class. You'll then need to configure your DEFAULT_PAGINATION_CLASS settings key to use your custom class as the default pagination style.",
"title": "Customizing the controls"
},
+ {
+ "location": "/api-guide/pagination/#low-level-api",
+ "text": "The low-level API for determining if a pagination class should display the controls or not is exposed as a display_page_controls attribute on the pagination instance. Custom pagination classes should be set to True in the paginate_queryset method if they require the HTML pagination controls to be displayed. The .to_html() and .get_html_context() methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.",
+ "title": "Low-level API"
+ },
{
"location": "/api-guide/pagination/#third-party-packages",
"text": "The following third party packages are also available.",
@@ -2162,14 +2817,34 @@
},
{
"location": "/api-guide/versioning/#versioning-with-rest-framework",
- "text": "When API versioning is enabled, the request.version attribute will contain a string that corresponds to the version requested in the incoming client request. By default, versioning is not enabled, and request.version will always return None . Varying behavior based on the version How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example: def get_serializer_class(self):\n if self.request.version == 'v1':\n return AccountSerializerVersion1\n return AccountSerializer Reversing URLs for versioned APIs The reverse function included by REST framework ties in with the versioning scheme. You need to make sure to include the current request as a keyword argument, like so. from rest_framework.reverse import reverse\n\nreverse('bookings-list', request=request) The above function will apply any URL transformations appropriate to the request version. For example: If NamespacedVersioning was being used, and the API version was 'v1', then the URL lookup used would be 'v1:bookings-list' , which might resolve to a URL like http://example.org/v1/bookings/ . If QueryParameterVersioning was being used, and the API version was 1.0 , then the returned URL might be something like http://example.org/bookings/?version=1.0 Versioned APIs and hyperlinked serializers When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer. def get(self, request):\n queryset = Booking.objects.all()\n serializer = BookingsSerializer(queryset, many=True, context={'request': request})\n return Response({'all_bookings': serializer.data}) Doing so will allow any returned URLs to include the appropriate versioning.",
+ "text": "When API versioning is enabled, the request.version attribute will contain a string that corresponds to the version requested in the incoming client request. By default, versioning is not enabled, and request.version will always return None .",
"title": "Versioning with REST framework"
},
+ {
+ "location": "/api-guide/versioning/#varying-behavior-based-on-the-version",
+ "text": "How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example: def get_serializer_class(self):\n if self.request.version == 'v1':\n return AccountSerializerVersion1\n return AccountSerializer",
+ "title": "Varying behavior based on the version"
+ },
+ {
+ "location": "/api-guide/versioning/#reversing-urls-for-versioned-apis",
+ "text": "The reverse function included by REST framework ties in with the versioning scheme. You need to make sure to include the current request as a keyword argument, like so. from rest_framework.reverse import reverse\n\nreverse('bookings-list', request=request) The above function will apply any URL transformations appropriate to the request version. For example: If NamespacedVersioning was being used, and the API version was 'v1', then the URL lookup used would be 'v1:bookings-list' , which might resolve to a URL like http://example.org/v1/bookings/ . If QueryParameterVersioning was being used, and the API version was 1.0 , then the returned URL might be something like http://example.org/bookings/?version=1.0",
+ "title": "Reversing URLs for versioned APIs"
+ },
+ {
+ "location": "/api-guide/versioning/#versioned-apis-and-hyperlinked-serializers",
+ "text": "When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer. def get(self, request):\n queryset = Booking.objects.all()\n serializer = BookingsSerializer(queryset, many=True, context={'request': request})\n return Response({'all_bookings': serializer.data}) Doing so will allow any returned URLs to include the appropriate versioning.",
+ "title": "Versioned APIs and hyperlinked serializers"
+ },
{
"location": "/api-guide/versioning/#configuring-the-versioning-scheme",
- "text": "The versioning scheme is defined by the DEFAULT_VERSIONING_CLASS settings key. REST_FRAMEWORK = {\n 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'\n} Unless it is explicitly set, the value for DEFAULT_VERSIONING_CLASS will be None . In this case the request.version attribute will always return None . You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the versioning_class attribute. class ProfileList(APIView):\n versioning_class = versioning.QueryParameterVersioning Other versioning settings The following settings keys are also used to control versioning: DEFAULT_VERSION . The value that should be used for request.version when no versioning information is present. Defaults to None . ALLOWED_VERSIONS . If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. Note that the value used for the DEFAULT_VERSION setting is always considered to be part of the ALLOWED_VERSIONS set. Defaults to None . VERSION_PARAM . The string that should used for any versioning parameters, such as in the media type or URL query parameters. Defaults to 'version' . You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the default_version , allowed_versions and version_param class variables. For example, if you want to use URLPathVersioning : from rest_framework.versioning import URLPathVersioning\nfrom rest_framework.views import APIView\n\nclass ExampleVersioning(URLPathVersioning):\n default_version = ...\n allowed_versions = ...\n version_param = ...\n\nclass ExampleView(APIVIew):\n versioning_class = ExampleVersioning",
+ "text": "The versioning scheme is defined by the DEFAULT_VERSIONING_CLASS settings key. REST_FRAMEWORK = {\n 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'\n} Unless it is explicitly set, the value for DEFAULT_VERSIONING_CLASS will be None . In this case the request.version attribute will always return None . You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the versioning_class attribute. class ProfileList(APIView):\n versioning_class = versioning.QueryParameterVersioning",
"title": "Configuring the versioning scheme"
},
+ {
+ "location": "/api-guide/versioning/#other-versioning-settings",
+ "text": "The following settings keys are also used to control versioning: DEFAULT_VERSION . The value that should be used for request.version when no versioning information is present. Defaults to None . ALLOWED_VERSIONS . If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. Note that the value used for the DEFAULT_VERSION setting is always considered to be part of the ALLOWED_VERSIONS set. Defaults to None . VERSION_PARAM . The string that should used for any versioning parameters, such as in the media type or URL query parameters. Defaults to 'version' . You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the default_version , allowed_versions and version_param class variables. For example, if you want to use URLPathVersioning : from rest_framework.versioning import URLPathVersioning\nfrom rest_framework.views import APIView\n\nclass ExampleVersioning(URLPathVersioning):\n default_version = ...\n allowed_versions = ...\n version_param = ...\n\nclass ExampleView(APIVIew):\n versioning_class = ExampleVersioning",
+ "title": "Other versioning settings"
+ },
{
"location": "/api-guide/versioning/#api-reference",
"text": "",
@@ -2177,9 +2852,14 @@
},
{
"location": "/api-guide/versioning/#acceptheaderversioning",
- "text": "This scheme requires the client to specify the version as part of the media type in the Accept header. The version is included as a media type parameter, that supplements the main media type. Here's an example HTTP request using the accept header versioning style. GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/json; version=1.0 In the example request above request.version attribute would return the string '1.0' . Versioning based on accept headers is generally considered as best practice , although other styles may be suitable depending on your client requirements. Using accept headers with vendor media types Strictly speaking the json media type is not specified as including additional parameters . If you are building a well-specified public API you might consider using a vendor media type . To do so, configure your renderers to use a JSON based renderer with a custom media type: class BookingsAPIRenderer(JSONRenderer):\n media_type = 'application/vnd.megacorp.bookings+json' Your client requests would now look like this: GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/vnd.megacorp.bookings+json; version=1.0",
+ "text": "This scheme requires the client to specify the version as part of the media type in the Accept header. The version is included as a media type parameter, that supplements the main media type. Here's an example HTTP request using the accept header versioning style. GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/json; version=1.0 In the example request above request.version attribute would return the string '1.0' . Versioning based on accept headers is generally considered as best practice , although other styles may be suitable depending on your client requirements.",
"title": "AcceptHeaderVersioning"
},
+ {
+ "location": "/api-guide/versioning/#using-accept-headers-with-vendor-media-types",
+ "text": "Strictly speaking the json media type is not specified as including additional parameters . If you are building a well-specified public API you might consider using a vendor media type . To do so, configure your renderers to use a JSON based renderer with a custom media type: class BookingsAPIRenderer(JSONRenderer):\n media_type = 'application/vnd.megacorp.bookings+json' Your client requests would now look like this: GET /bookings/ HTTP/1.1\nHost: example.com\nAccept: application/vnd.megacorp.bookings+json; version=1.0",
+ "title": "Using accept headers with vendor media types"
+ },
{
"location": "/api-guide/versioning/#urlpathversioning",
"text": "This scheme requires the client to specify the version as part of the URL path. GET /v1/bookings/ HTTP/1.1\nHost: example.com\nAccept: application/json Your URL conf must include a pattern that matches the version with a 'version' keyword argument, so that this information is available to the versioning scheme. urlpatterns = [\n url(\n r'^(?P version (v1|v2))/bookings/$',\n bookings_list,\n name='bookings-list'\n ),\n url(\n r'^(?P version (v1|v2))/bookings/(?P pk [0-9]+)/$',\n bookings_detail,\n name='bookings-detail'\n )\n]",
@@ -2282,9 +2962,14 @@
},
{
"location": "/api-guide/format-suffixes/#format_suffix_patterns",
- "text": "Signature : format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None) Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided. Arguments: urlpatterns : Required. A URL pattern list. suffix_required : Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to False , meaning that suffixes are optional by default. allowed : Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. Example: from rest_framework.urlpatterns import format_suffix_patterns\nfrom blog import views\n\nurlpatterns = [\n url(r'^/$', views.apt_root),\n url(r'^comments/$', views.comment_list),\n url(r'^comments/(?P pk [0-9]+)/$', views.comment_detail)\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) When using format_suffix_patterns , you must make sure to add the 'format' keyword argument to the corresponding views. For example: @api_view(('GET', 'POST'))\ndef comment_list(request, format=None):\n # do stuff... Or with class based views: class CommentList(APIView):\n def get(self, request, format=None):\n # do stuff...\n\n def post(self, request, format=None):\n # do stuff... The name of the kwarg used may be modified by using the FORMAT_SUFFIX_KWARG setting. Also note that format_suffix_patterns does not support descending into include URL patterns. Using with i18n_patterns If using the i18n_patterns function provided by Django, as well as format_suffix_patterns you should make sure that the i18n_patterns function is applied as the final, or outermost function. For example: url patterns = [\n \u2026\n]\n\nurlpatterns = i18n_patterns(\n format_suffix_patterns(urlpatterns, allowed=['json', 'html'])\n)",
+ "text": "Signature : format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None) Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided. Arguments: urlpatterns : Required. A URL pattern list. suffix_required : Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to False , meaning that suffixes are optional by default. allowed : Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. Example: from rest_framework.urlpatterns import format_suffix_patterns\nfrom blog import views\n\nurlpatterns = [\n url(r'^/$', views.apt_root),\n url(r'^comments/$', views.comment_list),\n url(r'^comments/(?P pk [0-9]+)/$', views.comment_detail)\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) When using format_suffix_patterns , you must make sure to add the 'format' keyword argument to the corresponding views. For example: @api_view(('GET', 'POST'))\ndef comment_list(request, format=None):\n # do stuff... Or with class based views: class CommentList(APIView):\n def get(self, request, format=None):\n # do stuff...\n\n def post(self, request, format=None):\n # do stuff... The name of the kwarg used may be modified by using the FORMAT_SUFFIX_KWARG setting. Also note that format_suffix_patterns does not support descending into include URL patterns.",
"title": "format_suffix_patterns"
},
+ {
+ "location": "/api-guide/format-suffixes/#using-with-i18n_patterns",
+ "text": "If using the i18n_patterns function provided by Django, as well as format_suffix_patterns you should make sure that the i18n_patterns function is applied as the final, or outermost function. For example: url patterns = [\n \u2026\n]\n\nurlpatterns = i18n_patterns(\n format_suffix_patterns(urlpatterns, allowed=['json', 'html'])\n)",
+ "title": "Using with i18n_patterns"
+ },
{
"location": "/api-guide/format-suffixes/#query-parameter-formats",
"text": "An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations. To select a representation using its short format, use the format query parameter. For example: http://example.com/organizations/?format=csv . The name of this query parameter can be modified using the URL_FORMAT_OVERRIDE setting. Set the value to None to disable this behavior.",
@@ -2452,9 +3137,24 @@
},
{
"location": "/api-guide/testing/#creating-test-requests",
- "text": "The APIRequestFactory class supports an almost identical API to Django's standard RequestFactory class. This means that the standard .get() , .post() , .put() , .patch() , .delete() , .head() and .options() methods are all available. from rest_framework.test import APIRequestFactory\n\n# Using the standard RequestFactory API to create a form POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'}) Using the format argument Methods which create a request body, such as post , put and patch , include a format argument, which make it easy to generate requests using a content type other than multipart form data. For example: # Create a JSON POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'}, format='json') By default the available formats are 'multipart' and 'json' . For compatibility with Django's existing RequestFactory the default format is 'multipart' . To support a wider set of request formats, or change the default format, see the configuration section . Explicitly encoding the request body If you need to explicitly encode the request body, you can do so by setting the content_type flag. For example: request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json') PUT and PATCH with form data One difference worth noting between Django's RequestFactory and REST framework's APIRequestFactory is that multipart form data will be encoded for methods other than just .post() . For example, using APIRequestFactory , you can make a form PUT request like so: factory = APIRequestFactory()\nrequest = factory.put('/notes/547/', {'title': 'remember to email dave'}) Using Django's RequestFactory , you'd need to explicitly encode the data yourself: from django.test.client import encode_multipart, RequestFactory\n\nfactory = RequestFactory()\ndata = {'title': 'remember to email dave'}\ncontent = encode_multipart('BoUnDaRyStRiNg', data)\ncontent_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'\nrequest = factory.put('/notes/547/', content, content_type=content_type)",
+ "text": "The APIRequestFactory class supports an almost identical API to Django's standard RequestFactory class. This means that the standard .get() , .post() , .put() , .patch() , .delete() , .head() and .options() methods are all available. from rest_framework.test import APIRequestFactory\n\n# Using the standard RequestFactory API to create a form POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'})",
"title": "Creating test requests"
},
+ {
+ "location": "/api-guide/testing/#using-the-format-argument",
+ "text": "Methods which create a request body, such as post , put and patch , include a format argument, which make it easy to generate requests using a content type other than multipart form data. For example: # Create a JSON POST request\nfactory = APIRequestFactory()\nrequest = factory.post('/notes/', {'title': 'new idea'}, format='json') By default the available formats are 'multipart' and 'json' . For compatibility with Django's existing RequestFactory the default format is 'multipart' . To support a wider set of request formats, or change the default format, see the configuration section .",
+ "title": "Using the format argument"
+ },
+ {
+ "location": "/api-guide/testing/#explicitly-encoding-the-request-body",
+ "text": "If you need to explicitly encode the request body, you can do so by setting the content_type flag. For example: request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')",
+ "title": "Explicitly encoding the request body"
+ },
+ {
+ "location": "/api-guide/testing/#put-and-patch-with-form-data",
+ "text": "One difference worth noting between Django's RequestFactory and REST framework's APIRequestFactory is that multipart form data will be encoded for methods other than just .post() . For example, using APIRequestFactory , you can make a form PUT request like so: factory = APIRequestFactory()\nrequest = factory.put('/notes/547/', {'title': 'remember to email dave'}) Using Django's RequestFactory , you'd need to explicitly encode the data yourself: from django.test.client import encode_multipart, RequestFactory\n\nfactory = RequestFactory()\ndata = {'title': 'remember to email dave'}\ncontent = encode_multipart('BoUnDaRyStRiNg', data)\ncontent_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'\nrequest = factory.put('/notes/547/', content, content_type=content_type)",
+ "title": "PUT and PATCH with form data"
+ },
{
"location": "/api-guide/testing/#forcing-authentication",
"text": "When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials. To forcibly authenticate a request, use the force_authenticate() method. from rest_framework.test import force_authenticate\n\nfactory = APIRequestFactory()\nuser = User.objects.get(username='olivia')\nview = AccountDetail.as_view()\n\n# Make an authenticated request to the view...\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user)\nresponse = view(request) The signature for the method is force_authenticate(request, user=None, token=None) . When making the call, either or both of the user and token may be set. For example, when forcibly authenticating using a token, you might do something like the following: user = User.objects.get(username='olivia')\nrequest = factory.get('/accounts/django-superstars/')\nforce_authenticate(request, user=user, token=user.token) Note : When using APIRequestFactory , the object that is returned is Django's standard HttpRequest , and not REST framework's Request object, which is only generated once the view is called. This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting .token directly will have no effect, and setting .user directly will only work if session authentication is being used. # Request will only authenticate if `SessionAuthentication` is in use.\nrequest = factory.get('/accounts/django-superstars/')\nrequest.user = user\nresponse = view(request)",
@@ -2477,9 +3177,24 @@
},
{
"location": "/api-guide/testing/#authenticating",
- "text": ".login(**kwargs) The login method functions exactly as it does with Django's regular Client class. This allows you to authenticate requests against any views which include SessionAuthentication . # Make all requests in the context of a logged in session.\nclient = APIClient()\nclient.login(username='lauren', password='secret') To logout, call the logout method as usual. # Log out\nclient.logout() The login method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API. .credentials(**kwargs) The credentials method can be used to set headers that will then be included on all subsequent requests by the test client. from rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\n# Include an appropriate `Authorization:` header on all requests.\ntoken = Token.objects.get(user__username='lauren')\nclient = APIClient()\nclient.credentials(HTTP_AUTHORIZATION='Token ' + token.key) Note that calling credentials a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments. # Stop including any credentials\nclient.credentials() The credentials method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes. .force_authenticate(user=None, token=None) Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated. This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests. user = User.objects.get(username='lauren')\nclient = APIClient()\nclient.force_authenticate(user=user) To unauthenticate subsequent requests, call force_authenticate setting the user and/or token to None . client.force_authenticate(user=None)",
+ "text": "",
"title": "Authenticating"
},
+ {
+ "location": "/api-guide/testing/#loginkwargs",
+ "text": "The login method functions exactly as it does with Django's regular Client class. This allows you to authenticate requests against any views which include SessionAuthentication . # Make all requests in the context of a logged in session.\nclient = APIClient()\nclient.login(username='lauren', password='secret') To logout, call the logout method as usual. # Log out\nclient.logout() The login method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.",
+ "title": ".login(**kwargs)"
+ },
+ {
+ "location": "/api-guide/testing/#credentialskwargs",
+ "text": "The credentials method can be used to set headers that will then be included on all subsequent requests by the test client. from rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\n# Include an appropriate `Authorization:` header on all requests.\ntoken = Token.objects.get(user__username='lauren')\nclient = APIClient()\nclient.credentials(HTTP_AUTHORIZATION='Token ' + token.key) Note that calling credentials a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments. # Stop including any credentials\nclient.credentials() The credentials method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.",
+ "title": ".credentials(**kwargs)"
+ },
+ {
+ "location": "/api-guide/testing/#force_authenticateusernone-tokennone",
+ "text": "Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated. This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests. user = User.objects.get(username='lauren')\nclient = APIClient()\nclient.force_authenticate(user=user) To unauthenticate subsequent requests, call force_authenticate setting the user and/or token to None . client.force_authenticate(user=None)",
+ "title": ".force_authenticate(user=None, token=None)"
+ },
{
"location": "/api-guide/testing/#csrf-validation",
"text": "By default CSRF validation is not applied when using APIClient . If you need to explicitly enable CSRF validation, you can do so by setting the enforce_csrf_checks flag when instantiating the client. client = APIClient(enforce_csrf_checks=True) As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling login() .",
@@ -2547,54 +3262,244 @@
},
{
"location": "/api-guide/settings/#api-policy-settings",
- "text": "The following settings control the basic API policies, and are applied to every APIView class based view, or @api_view function based view. DEFAULT_RENDERER_CLASSES A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a Response object. Default: (\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n) DEFAULT_PARSER_CLASSES A list or tuple of parser classes, that determines the default set of parsers used when accessing the request.data property. Default: (\n 'rest_framework.parsers.JSONParser',\n 'rest_framework.parsers.FormParser',\n 'rest_framework.parsers.MultiPartParser'\n) DEFAULT_AUTHENTICATION_CLASSES A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.user or request.auth properties. Default: (\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.BasicAuthentication'\n) DEFAULT_PERMISSION_CLASSES A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list. Default: (\n 'rest_framework.permissions.AllowAny',\n) DEFAULT_THROTTLE_CLASSES A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view. Default: () DEFAULT_CONTENT_NEGOTIATION_CLASS A content negotiation class, that determines how a renderer is selected for the response, given an incoming request. Default: 'rest_framework.negotiation.DefaultContentNegotiation'",
+ "text": "The following settings control the basic API policies, and are applied to every APIView class based view, or @api_view function based view.",
"title": "API policy settings"
},
+ {
+ "location": "/api-guide/settings/#default_renderer_classes",
+ "text": "A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a Response object. Default: (\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n)",
+ "title": "DEFAULT_RENDERER_CLASSES"
+ },
+ {
+ "location": "/api-guide/settings/#default_parser_classes",
+ "text": "A list or tuple of parser classes, that determines the default set of parsers used when accessing the request.data property. Default: (\n 'rest_framework.parsers.JSONParser',\n 'rest_framework.parsers.FormParser',\n 'rest_framework.parsers.MultiPartParser'\n)",
+ "title": "DEFAULT_PARSER_CLASSES"
+ },
+ {
+ "location": "/api-guide/settings/#default_authentication_classes",
+ "text": "A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request.user or request.auth properties. Default: (\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.BasicAuthentication'\n)",
+ "title": "DEFAULT_AUTHENTICATION_CLASSES"
+ },
+ {
+ "location": "/api-guide/settings/#default_permission_classes",
+ "text": "A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list. Default: (\n 'rest_framework.permissions.AllowAny',\n)",
+ "title": "DEFAULT_PERMISSION_CLASSES"
+ },
+ {
+ "location": "/api-guide/settings/#default_throttle_classes",
+ "text": "A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view. Default: ()",
+ "title": "DEFAULT_THROTTLE_CLASSES"
+ },
+ {
+ "location": "/api-guide/settings/#default_content_negotiation_class",
+ "text": "A content negotiation class, that determines how a renderer is selected for the response, given an incoming request. Default: 'rest_framework.negotiation.DefaultContentNegotiation'",
+ "title": "DEFAULT_CONTENT_NEGOTIATION_CLASS"
+ },
{
"location": "/api-guide/settings/#generic-view-settings",
- "text": "The following settings control the behavior of the generic class based views. DEFAULT_PAGINATION_SERIALIZER_CLASS This setting has been removed. The pagination API does not use serializers to determine the output format, and\nyou'll need to instead override the `get_paginated_response method on a\npagination class in order to specify how the output format is controlled. DEFAULT_FILTER_BACKENDS A list of filter backend classes that should be used for generic filtering.\nIf set to None then generic filtering is disabled. PAGINATE_BY This setting has been removed. See the pagination documentation for further guidance on setting the pagination style . PAGE_SIZE The default page size to use for pagination. If set to None , pagination is disabled by default. Default: None PAGINATE_BY_PARAM This setting has been removed. See the pagination documentation for further guidance on setting the pagination style . MAX_PAGINATE_BY This setting is pending deprecation. See the pagination documentation for further guidance on setting the pagination style . SEARCH_PARAM The name of a query parameter, which can be used to specify the search term used by SearchFilter . Default: search ORDERING_PARAM The name of a query parameter, which can be used to specify the ordering of results returned by OrderingFilter . Default: ordering",
+ "text": "The following settings control the behavior of the generic class based views.",
"title": "Generic view settings"
},
+ {
+ "location": "/api-guide/settings/#default_pagination_serializer_class",
+ "text": "This setting has been removed. The pagination API does not use serializers to determine the output format, and\nyou'll need to instead override the `get_paginated_response method on a\npagination class in order to specify how the output format is controlled.",
+ "title": "DEFAULT_PAGINATION_SERIALIZER_CLASS"
+ },
+ {
+ "location": "/api-guide/settings/#default_filter_backends",
+ "text": "A list of filter backend classes that should be used for generic filtering.\nIf set to None then generic filtering is disabled.",
+ "title": "DEFAULT_FILTER_BACKENDS"
+ },
+ {
+ "location": "/api-guide/settings/#paginate_by",
+ "text": "This setting has been removed. See the pagination documentation for further guidance on setting the pagination style .",
+ "title": "PAGINATE_BY"
+ },
+ {
+ "location": "/api-guide/settings/#page_size",
+ "text": "The default page size to use for pagination. If set to None , pagination is disabled by default. Default: None",
+ "title": "PAGE_SIZE"
+ },
+ {
+ "location": "/api-guide/settings/#paginate_by_param",
+ "text": "This setting has been removed. See the pagination documentation for further guidance on setting the pagination style .",
+ "title": "PAGINATE_BY_PARAM"
+ },
+ {
+ "location": "/api-guide/settings/#max_paginate_by",
+ "text": "This setting is pending deprecation. See the pagination documentation for further guidance on setting the pagination style .",
+ "title": "MAX_PAGINATE_BY"
+ },
+ {
+ "location": "/api-guide/settings/#search_param",
+ "text": "The name of a query parameter, which can be used to specify the search term used by SearchFilter . Default: search",
+ "title": "SEARCH_PARAM"
+ },
+ {
+ "location": "/api-guide/settings/#ordering_param",
+ "text": "The name of a query parameter, which can be used to specify the ordering of results returned by OrderingFilter . Default: ordering",
+ "title": "ORDERING_PARAM"
+ },
{
"location": "/api-guide/settings/#versioning-settings",
- "text": "DEFAULT_VERSION The value that should be used for request.version when no versioning information is present. Default: None ALLOWED_VERSIONS If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. Default: None VERSION_PARAMETER The string that should used for any versioning parameters, such as in the media type or URL query parameters. Default: 'version'",
+ "text": "",
"title": "Versioning settings"
},
+ {
+ "location": "/api-guide/settings/#default_version",
+ "text": "The value that should be used for request.version when no versioning information is present. Default: None",
+ "title": "DEFAULT_VERSION"
+ },
+ {
+ "location": "/api-guide/settings/#allowed_versions",
+ "text": "If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. Default: None",
+ "title": "ALLOWED_VERSIONS"
+ },
+ {
+ "location": "/api-guide/settings/#version_parameter",
+ "text": "The string that should used for any versioning parameters, such as in the media type or URL query parameters. Default: 'version'",
+ "title": "VERSION_PARAMETER"
+ },
{
"location": "/api-guide/settings/#authentication-settings",
- "text": "The following settings control the behavior of unauthenticated requests. UNAUTHENTICATED_USER The class that should be used to initialize request.user for unauthenticated requests. Default: django.contrib.auth.models.AnonymousUser UNAUTHENTICATED_TOKEN The class that should be used to initialize request.auth for unauthenticated requests. Default: None",
+ "text": "The following settings control the behavior of unauthenticated requests.",
"title": "Authentication settings"
},
+ {
+ "location": "/api-guide/settings/#unauthenticated_user",
+ "text": "The class that should be used to initialize request.user for unauthenticated requests. Default: django.contrib.auth.models.AnonymousUser",
+ "title": "UNAUTHENTICATED_USER"
+ },
+ {
+ "location": "/api-guide/settings/#unauthenticated_token",
+ "text": "The class that should be used to initialize request.auth for unauthenticated requests. Default: None",
+ "title": "UNAUTHENTICATED_TOKEN"
+ },
{
"location": "/api-guide/settings/#test-settings",
- "text": "The following settings control the behavior of APIRequestFactory and APIClient TEST_REQUEST_DEFAULT_FORMAT The default format that should be used when making test requests. This should match up with the format of one of the renderer classes in the TEST_REQUEST_RENDERER_CLASSES setting. Default: 'multipart' TEST_REQUEST_RENDERER_CLASSES The renderer classes that are supported when building test requests. The format of any of these renderer classes may be used when constructing a test request, for example: client.post('/users', {'username': 'jamie'}, format='json') Default: (\n 'rest_framework.renderers.MultiPartRenderer',\n 'rest_framework.renderers.JSONRenderer'\n)",
+ "text": "The following settings control the behavior of APIRequestFactory and APIClient",
"title": "Test settings"
},
+ {
+ "location": "/api-guide/settings/#test_request_default_format",
+ "text": "The default format that should be used when making test requests. This should match up with the format of one of the renderer classes in the TEST_REQUEST_RENDERER_CLASSES setting. Default: 'multipart'",
+ "title": "TEST_REQUEST_DEFAULT_FORMAT"
+ },
+ {
+ "location": "/api-guide/settings/#test_request_renderer_classes",
+ "text": "The renderer classes that are supported when building test requests. The format of any of these renderer classes may be used when constructing a test request, for example: client.post('/users', {'username': 'jamie'}, format='json') Default: (\n 'rest_framework.renderers.MultiPartRenderer',\n 'rest_framework.renderers.JSONRenderer'\n)",
+ "title": "TEST_REQUEST_RENDERER_CLASSES"
+ },
{
"location": "/api-guide/settings/#content-type-controls",
- "text": "URL_FORMAT_OVERRIDE The name of a URL parameter that may be used to override the default content negotiation Accept header behavior, by using a format=\u2026 query parameter in the request URL. For example: http://example.com/organizations/?format=csv If the value of this setting is None then URL format overrides will be disabled. Default: 'format' FORMAT_SUFFIX_KWARG The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using format_suffix_patterns to include suffixed URL patterns. For example: http://example.com/organizations.csv/ Default: 'format'",
+ "text": "",
"title": "Content type controls"
},
+ {
+ "location": "/api-guide/settings/#url_format_override",
+ "text": "The name of a URL parameter that may be used to override the default content negotiation Accept header behavior, by using a format=\u2026 query parameter in the request URL. For example: http://example.com/organizations/?format=csv If the value of this setting is None then URL format overrides will be disabled. Default: 'format'",
+ "title": "URL_FORMAT_OVERRIDE"
+ },
+ {
+ "location": "/api-guide/settings/#format_suffix_kwarg",
+ "text": "The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using format_suffix_patterns to include suffixed URL patterns. For example: http://example.com/organizations.csv/ Default: 'format'",
+ "title": "FORMAT_SUFFIX_KWARG"
+ },
{
"location": "/api-guide/settings/#date-and-time-formatting",
- "text": "The following settings are used to control how date and time representations may be parsed and rendered. DATETIME_FORMAT A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None , then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer. May be any of None , 'iso-8601' or a Python strftime format string. Default: 'iso-8601' DATETIME_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to DateTimeField serializer fields. May be a list including the string 'iso-8601' or Python strftime format strings. Default: ['iso-8601'] DATE_FORMAT A format string that should be used by default for rendering the output of DateField serializer fields. If None , then DateField serializer fields will return Python date objects, and the date encoding will be determined by the renderer. May be any of None , 'iso-8601' or a Python strftime format string. Default: 'iso-8601' DATE_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to DateField serializer fields. May be a list including the string 'iso-8601' or Python strftime format strings. Default: ['iso-8601'] TIME_FORMAT A format string that should be used by default for rendering the output of TimeField serializer fields. If None , then TimeField serializer fields will return Python time objects, and the time encoding will be determined by the renderer. May be any of None , 'iso-8601' or a Python strftime format string. Default: 'iso-8601' TIME_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to TimeField serializer fields. May be a list including the string 'iso-8601' or Python strftime format strings. Default: ['iso-8601']",
+ "text": "The following settings are used to control how date and time representations may be parsed and rendered.",
"title": "Date and time formatting"
},
+ {
+ "location": "/api-guide/settings/#datetime_format",
+ "text": "A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None , then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer. May be any of None , 'iso-8601' or a Python strftime format string. Default: 'iso-8601'",
+ "title": "DATETIME_FORMAT"
+ },
+ {
+ "location": "/api-guide/settings/#datetime_input_formats",
+ "text": "A list of format strings that should be used by default for parsing inputs to DateTimeField serializer fields. May be a list including the string 'iso-8601' or Python strftime format strings. Default: ['iso-8601']",
+ "title": "DATETIME_INPUT_FORMATS"
+ },
+ {
+ "location": "/api-guide/settings/#date_format",
+ "text": "A format string that should be used by default for rendering the output of DateField serializer fields. If None , then DateField serializer fields will return Python date objects, and the date encoding will be determined by the renderer. May be any of None , 'iso-8601' or a Python strftime format string. Default: 'iso-8601'",
+ "title": "DATE_FORMAT"
+ },
+ {
+ "location": "/api-guide/settings/#date_input_formats",
+ "text": "A list of format strings that should be used by default for parsing inputs to DateField serializer fields. May be a list including the string 'iso-8601' or Python strftime format strings. Default: ['iso-8601']",
+ "title": "DATE_INPUT_FORMATS"
+ },
+ {
+ "location": "/api-guide/settings/#time_format",
+ "text": "A format string that should be used by default for rendering the output of TimeField serializer fields. If None , then TimeField serializer fields will return Python time objects, and the time encoding will be determined by the renderer. May be any of None , 'iso-8601' or a Python strftime format string. Default: 'iso-8601'",
+ "title": "TIME_FORMAT"
+ },
+ {
+ "location": "/api-guide/settings/#time_input_formats",
+ "text": "A list of format strings that should be used by default for parsing inputs to TimeField serializer fields. May be a list including the string 'iso-8601' or Python strftime format strings. Default: ['iso-8601']",
+ "title": "TIME_INPUT_FORMATS"
+ },
{
"location": "/api-guide/settings/#encodings",
- "text": "UNICODE_JSON When set to True , JSON responses will allow unicode characters in responses. For example: {\"unicode black star\":\"\u2605\"} When set to False , JSON responses will escape non-ascii characters, like so: {\"unicode black star\":\"\\u2605\"} Both styles conform to RFC 4627 , and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses. Default: True COMPACT_JSON When set to True , JSON responses will return compact representations, with no spacing after ':' and ',' characters. For example: {\"is_admin\":false,\"email\":\"jane@example\"} When set to False , JSON responses will return slightly more verbose representations, like so: {\"is_admin\": false, \"email\": \"jane@example\"} The default style is to return minified responses, in line with Heroku's API design guidelines . Default: True COERCE_DECIMAL_TO_STRING When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations. When set to True , the serializer DecimalField class will return strings instead of Decimal objects. When set to False , serializers will return Decimal objects, which the default JSON encoder will return as floats. Default: True",
+ "text": "",
"title": "Encodings"
},
+ {
+ "location": "/api-guide/settings/#unicode_json",
+ "text": "When set to True , JSON responses will allow unicode characters in responses. For example: {\"unicode black star\":\"\u2605\"} When set to False , JSON responses will escape non-ascii characters, like so: {\"unicode black star\":\"\\u2605\"} Both styles conform to RFC 4627 , and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses. Default: True",
+ "title": "UNICODE_JSON"
+ },
+ {
+ "location": "/api-guide/settings/#compact_json",
+ "text": "When set to True , JSON responses will return compact representations, with no spacing after ':' and ',' characters. For example: {\"is_admin\":false,\"email\":\"jane@example\"} When set to False , JSON responses will return slightly more verbose representations, like so: {\"is_admin\": false, \"email\": \"jane@example\"} The default style is to return minified responses, in line with Heroku's API design guidelines . Default: True",
+ "title": "COMPACT_JSON"
+ },
+ {
+ "location": "/api-guide/settings/#coerce_decimal_to_string",
+ "text": "When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations. When set to True , the serializer DecimalField class will return strings instead of Decimal objects. When set to False , serializers will return Decimal objects, which the default JSON encoder will return as floats. Default: True",
+ "title": "COERCE_DECIMAL_TO_STRING"
+ },
{
"location": "/api-guide/settings/#view-names-and-descriptions",
- "text": "The following settings are used to generate the view names and descriptions, as used in responses to OPTIONS requests, and as used in the browsable API. VIEW_NAME_FUNCTION A string representing the function that should be used when generating view names. This should be a function with the following signature: view_name(cls, suffix=None) cls : The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing cls.__name__ . suffix : The optional suffix used when differentiating individual views in a viewset. Default: 'rest_framework.views.get_view_name' VIEW_DESCRIPTION_FUNCTION A string representing the function that should be used when generating view descriptions. This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support rst markup in your view docstrings being output in the browsable API. This should be a function with the following signature: view_description(cls, html=False) cls : The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing cls.__doc__ html : A boolean indicating if HTML output is required. True when used in the browsable API, and False when used in generating OPTIONS responses. Default: 'rest_framework.views.get_view_description'",
+ "text": "The following settings are used to generate the view names and descriptions, as used in responses to OPTIONS requests, and as used in the browsable API.",
"title": "View names and descriptions"
},
+ {
+ "location": "/api-guide/settings/#view_name_function",
+ "text": "A string representing the function that should be used when generating view names. This should be a function with the following signature: view_name(cls, suffix=None) cls : The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing cls.__name__ . suffix : The optional suffix used when differentiating individual views in a viewset. Default: 'rest_framework.views.get_view_name'",
+ "title": "VIEW_NAME_FUNCTION"
+ },
+ {
+ "location": "/api-guide/settings/#view_description_function",
+ "text": "A string representing the function that should be used when generating view descriptions. This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support rst markup in your view docstrings being output in the browsable API. This should be a function with the following signature: view_description(cls, html=False) cls : The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing cls.__doc__ html : A boolean indicating if HTML output is required. True when used in the browsable API, and False when used in generating OPTIONS responses. Default: 'rest_framework.views.get_view_description'",
+ "title": "VIEW_DESCRIPTION_FUNCTION"
+ },
{
"location": "/api-guide/settings/#miscellaneous-settings",
- "text": "EXCEPTION_HANDLER A string representing the function that should be used when returning a response for any given exception. If the function returns None , a 500 error will be raised. This setting can be changed to support error responses other than the default {\"detail\": \"Failure...\"} responses. For example, you can use it to provide API responses like {\"errors\": [{\"message\": \"Failure...\", \"code\": \"\"} ...]} . This should be a function with the following signature: exception_handler(exc, context) exc : The exception. Default: 'rest_framework.views.exception_handler' NON_FIELD_ERRORS_KEY A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors. Default: 'non_field_errors' URL_FIELD_NAME A string representing the key that should be used for the URL fields generated by HyperlinkedModelSerializer . Default: 'url' NUM_PROXIES An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to None then less strict IP matching will be used by the throttle classes. Default: None",
+ "text": "",
"title": "Miscellaneous settings"
},
+ {
+ "location": "/api-guide/settings/#exception_handler",
+ "text": "A string representing the function that should be used when returning a response for any given exception. If the function returns None , a 500 error will be raised. This setting can be changed to support error responses other than the default {\"detail\": \"Failure...\"} responses. For example, you can use it to provide API responses like {\"errors\": [{\"message\": \"Failure...\", \"code\": \"\"} ...]} . This should be a function with the following signature: exception_handler(exc, context) exc : The exception. Default: 'rest_framework.views.exception_handler'",
+ "title": "EXCEPTION_HANDLER"
+ },
+ {
+ "location": "/api-guide/settings/#non_field_errors_key",
+ "text": "A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors. Default: 'non_field_errors'",
+ "title": "NON_FIELD_ERRORS_KEY"
+ },
+ {
+ "location": "/api-guide/settings/#url_field_name",
+ "text": "A string representing the key that should be used for the URL fields generated by HyperlinkedModelSerializer . Default: 'url'",
+ "title": "URL_FIELD_NAME"
+ },
+ {
+ "location": "/api-guide/settings/#num_proxies",
+ "text": "An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to None then less strict IP matching will be used by the throttle classes. Default: None",
+ "title": "NUM_PROXIES"
+ },
{
"location": "/topics/documenting-your-api/",
"text": "Documenting your API\n\n\n\n\nA REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.\n\n\n Roy Fielding, \nREST APIs must be hypertext driven\n\n\n\n\nThere are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.\n\n\nEndpoint documentation\n\n\nThe most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.\n\n\n\n\nDRF Docs\n\n\nDRF Docs\n allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the \nwebsite\n while there is also a \ndemo\n available for people to see what it looks like. \nLive API Endpoints\n allow you to utilize the endpoints from within the documentation in a neat way.\n\n\nFeatures include customizing the template with your branding, settings for hiding the docs depending on the environment and more.\n\n\nBoth this package and Django REST Swagger are fully documented, well supported, and come highly recommended.\n\n\n\n\n\n\nDjango REST Swagger\n\n\nMarc Gibbons' \nDjango REST Swagger\n integrates REST framework with the \nSwagger\n API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.\n\n\nDjango REST Swagger supports REST framework versions 2.3 and above.\n\n\nMark is also the author of the \nREST Framework Docs\n package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger.\n\n\nBoth this package and DRF docs are fully documented, well supported, and come highly recommended.\n\n\n\n\n\n\nApiary\n\n\nThere are various other online tools and services for providing API documentation. One notable service is \nApiary\n. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing \n prototyping, and various other tools.\n\n\n\n\n\n\nSelf describing APIs\n\n\nThe browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.\n\n\n\n\n\n\nSetting the title\n\n\nThe title that is used in the browsable API is generated from the view class name or function name. Any trailing \nView\n or \nViewSet\n suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.\n\n\nFor example, the view \nUserListView\n, will be named \nUser List\n when presented in the browsable API.\n\n\nWhen working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set \nUserViewSet\n will generate views named \nUser List\n and \nUser Instance\n.\n\n\nSetting the description\n\n\nThe description in the browsable API is generated from the docstring of the view or viewset.\n\n\nIf the python \nmarkdown\n library is installed, then \nmarkdown syntax\n may be used in the docstring, and will be converted to HTML in the browsable API. For example:\n\n\nclass AccountListView(views.APIView):\n \"\"\"\n Returns a list of all **active** accounts in the system.\n\n For more details on how accounts are activated please [see here][ref].\n\n [ref]: http://example.com/activating-accounts\n \"\"\"\n\n\n\nNote that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.\n\n\nThe \nOPTIONS\n method\n\n\nREST framework APIs also support programmatically accessible descriptions, using the \nOPTIONS\n HTTP method. A view will respond to an \nOPTIONS\n request with metadata including the name, description, and the various media types it accepts and responds with.\n\n\nWhen using the generic views, any \nOPTIONS\n requests will additionally respond with metadata regarding any \nPOST\n or \nPUT\n actions available, describing which fields are on the serializer.\n\n\nYou can modify the response behavior to \nOPTIONS\n requests by overriding the \nmetadata\n view method. For example:\n\n\ndef metadata(self, request):\n \"\"\"\n Don't include the view description in OPTIONS responses.\n \"\"\"\n data = super(ExampleView, self).metadata(request)\n data.pop('description')\n return data\n\n\n\n\n\nThe hypermedia approach\n\n\nTo be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.\n\n\nIn this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the \nmedia types\n that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.\n\n\nTo implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The \nREST, Hypermedia \n HATEOAS\n section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.",
@@ -2607,14 +3512,44 @@
},
{
"location": "/topics/documenting-your-api/#endpoint-documentation",
- "text": "The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way. DRF Docs DRF Docs allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the website while there is also a demo available for people to see what it looks like. Live API Endpoints allow you to utilize the endpoints from within the documentation in a neat way. Features include customizing the template with your branding, settings for hiding the docs depending on the environment and more. Both this package and Django REST Swagger are fully documented, well supported, and come highly recommended. Django REST Swagger Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints. Django REST Swagger supports REST framework versions 2.3 and above. Mark is also the author of the REST Framework Docs package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger. Both this package and DRF docs are fully documented, well supported, and come highly recommended. Apiary There are various other online tools and services for providing API documentation. One notable service is Apiary . With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing prototyping, and various other tools.",
+ "text": "The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.",
"title": "Endpoint documentation"
},
+ {
+ "location": "/topics/documenting-your-api/#drf-docs",
+ "text": "DRF Docs allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the website while there is also a demo available for people to see what it looks like. Live API Endpoints allow you to utilize the endpoints from within the documentation in a neat way. Features include customizing the template with your branding, settings for hiding the docs depending on the environment and more. Both this package and Django REST Swagger are fully documented, well supported, and come highly recommended.",
+ "title": "DRF Docs"
+ },
+ {
+ "location": "/topics/documenting-your-api/#django-rest-swagger",
+ "text": "Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints. Django REST Swagger supports REST framework versions 2.3 and above. Mark is also the author of the REST Framework Docs package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger. Both this package and DRF docs are fully documented, well supported, and come highly recommended.",
+ "title": "Django REST Swagger"
+ },
+ {
+ "location": "/topics/documenting-your-api/#apiary",
+ "text": "There are various other online tools and services for providing API documentation. One notable service is Apiary . With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing prototyping, and various other tools.",
+ "title": "Apiary"
+ },
{
"location": "/topics/documenting-your-api/#self-describing-apis",
- "text": "The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser. Setting the title The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores. For example, the view UserListView , will be named User List when presented in the browsable API. When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set UserViewSet will generate views named User List and User Instance . Setting the description The description in the browsable API is generated from the docstring of the view or viewset. If the python markdown library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example: class AccountListView(views.APIView):\n \"\"\"\n Returns a list of all **active** accounts in the system.\n\n For more details on how accounts are activated please [see here][ref].\n\n [ref]: http://example.com/activating-accounts\n \"\"\" Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view. The OPTIONS method REST framework APIs also support programmatically accessible descriptions, using the OPTIONS HTTP method. A view will respond to an OPTIONS request with metadata including the name, description, and the various media types it accepts and responds with. When using the generic views, any OPTIONS requests will additionally respond with metadata regarding any POST or PUT actions available, describing which fields are on the serializer. You can modify the response behavior to OPTIONS requests by overriding the metadata view method. For example: def metadata(self, request):\n \"\"\"\n Don't include the view description in OPTIONS responses.\n \"\"\"\n data = super(ExampleView, self).metadata(request)\n data.pop('description')\n return data",
+ "text": "The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.",
"title": "Self describing APIs"
},
+ {
+ "location": "/topics/documenting-your-api/#setting-the-title",
+ "text": "The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores. For example, the view UserListView , will be named User List when presented in the browsable API. When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set UserViewSet will generate views named User List and User Instance .",
+ "title": "Setting the title"
+ },
+ {
+ "location": "/topics/documenting-your-api/#setting-the-description",
+ "text": "The description in the browsable API is generated from the docstring of the view or viewset. If the python markdown library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example: class AccountListView(views.APIView):\n \"\"\"\n Returns a list of all **active** accounts in the system.\n\n For more details on how accounts are activated please [see here][ref].\n\n [ref]: http://example.com/activating-accounts\n \"\"\" Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.",
+ "title": "Setting the description"
+ },
+ {
+ "location": "/topics/documenting-your-api/#the-options-method",
+ "text": "REST framework APIs also support programmatically accessible descriptions, using the OPTIONS HTTP method. A view will respond to an OPTIONS request with metadata including the name, description, and the various media types it accepts and responds with. When using the generic views, any OPTIONS requests will additionally respond with metadata regarding any POST or PUT actions available, describing which fields are on the serializer. You can modify the response behavior to OPTIONS requests by overriding the metadata view method. For example: def metadata(self, request):\n \"\"\"\n Don't include the view description in OPTIONS responses.\n \"\"\"\n data = super(ExampleView, self).metadata(request)\n data.pop('description')\n return data",
+ "title": "The OPTIONS method"
+ },
{
"location": "/topics/documenting-your-api/#the-hypermedia-approach",
"text": "To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends. In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document. To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The REST, Hypermedia HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.",
@@ -2632,14 +3567,24 @@
},
{
"location": "/topics/internationalization/#enabling-internationalized-apis",
- "text": "You can change the default language by using the standard Django LANGUAGE_CODE setting: LANGUAGE_CODE = \"es-es\" You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE_CLASSES setting: MIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n] When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type: Request GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org Response HTTP/1.0 406 NOT ACCEPTABLE\n\n{\"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"} REST framework includes these built-in translations both for standard exception cases, and for serializer validation errors. Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example 400 Bad Request response body might look like this: {\"detail\": {\"username\": [\"Esse campo deve ser unico.\"]}} If you want to use different string for parts of the response such as detail and non_field_errors then you can modify this behavior by using a custom exception handler . Specifying the set of supported languages. By default all available languages will be supported. If you only wish to support a subset of the available languages, use Django's standard LANGUAGES setting: LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]",
+ "text": "You can change the default language by using the standard Django LANGUAGE_CODE setting: LANGUAGE_CODE = \"es-es\" You can turn on per-request language requests by adding LocalMiddleware to your MIDDLEWARE_CLASSES setting: MIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n] When per-request internationalization is enabled, client requests will respect the Accept-Language header where possible. For example, let's make a request for an unsupported media type: Request GET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org Response HTTP/1.0 406 NOT ACCEPTABLE\n\n{\"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"} REST framework includes these built-in translations both for standard exception cases, and for serializer validation errors. Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example 400 Bad Request response body might look like this: {\"detail\": {\"username\": [\"Esse campo deve ser unico.\"]}} If you want to use different string for parts of the response such as detail and non_field_errors then you can modify this behavior by using a custom exception handler .",
"title": "Enabling internationalized APIs"
},
+ {
+ "location": "/topics/internationalization/#specifying-the-set-of-supported-languages",
+ "text": "By default all available languages will be supported. If you only wish to support a subset of the available languages, use Django's standard LANGUAGES setting: LANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]",
+ "title": "Specifying the set of supported languages."
+ },
{
"location": "/topics/internationalization/#adding-new-translations",
- "text": "REST framework translations are managed online using Transifex . You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package. Sometimes you may need to add translation strings to your project locally. You may need to do this if: You want to use REST Framework in a language which has not been translated yet on Transifex. Your project includes custom error messages, which are not part of REST framework's default translation strings. Translating a new language locally This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading Django's translation docs . If you're translating a new language you'll need to translate the existing REST framework error messages: Make a new folder where you want to store the internationalization resources. Add this path to your LOCALE_PATHS setting. Now create a subfolder for the language you want to translate. The folder should be named using locale name notation. For example: de , pt_BR , es_AR . Now copy the base translations file from the REST framework source code into your translations folder. Edit the django.po file you've just copied, translating all the error messages. Run manage.py compilemessages -l pt_BR to make the translations \navailable for Django to use. You should see a message like processing file django.po in ... /locale/pt_BR/LC_MESSAGES . Restart your development server to see the changes take effect. If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source django.po file into a LOCALE_PATHS folder, and can instead simply run Django's standard makemessages process.",
+ "text": "REST framework translations are managed online using Transifex . You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package. Sometimes you may need to add translation strings to your project locally. You may need to do this if: You want to use REST Framework in a language which has not been translated yet on Transifex. Your project includes custom error messages, which are not part of REST framework's default translation strings.",
"title": "Adding new translations"
},
+ {
+ "location": "/topics/internationalization/#translating-a-new-language-locally",
+ "text": "This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading Django's translation docs . If you're translating a new language you'll need to translate the existing REST framework error messages: Make a new folder where you want to store the internationalization resources. Add this path to your LOCALE_PATHS setting. Now create a subfolder for the language you want to translate. The folder should be named using locale name notation. For example: de , pt_BR , es_AR . Now copy the base translations file from the REST framework source code into your translations folder. Edit the django.po file you've just copied, translating all the error messages. Run manage.py compilemessages -l pt_BR to make the translations \navailable for Django to use. You should see a message like processing file django.po in ... /locale/pt_BR/LC_MESSAGES . Restart your development server to see the changes take effect. If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source django.po file into a LOCALE_PATHS folder, and can instead simply run Django's standard makemessages process.",
+ "title": "Translating a new language locally"
+ },
{
"location": "/topics/internationalization/#how-the-language-is-determined",
"text": "If you want to allow per-request language preferences you'll need to include django.middleware.locale.LocaleMiddleware in your MIDDLEWARE_CLASSES setting. You can find more information on how the language preference is determined in the Django documentation . For reference, the method is: First, it looks for the language prefix in the requested URL. Failing that, it looks for the LANGUAGE_SESSION_KEY key in the current user\u2019s session. Failing that, it looks for a cookie. Failing that, it looks at the Accept-Language HTTP header. Failing that, it uses the global LANGUAGE_CODE setting. For API clients the most appropriate of these will typically be to use the Accept-Language header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an Accept-Language header for API clients rather than using language URL prefixes.",
@@ -2653,7 +3598,7 @@
{
"location": "/topics/ajax-csrf-cors/#working-with-ajax-csrf-cors",
"text": "\"Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one.\" Jeff Atwood",
- "title": "Working with AJAX, CSRF CORS"
+ "title": "Working with AJAX, CSRF & CORS"
},
{
"location": "/topics/ajax-csrf-cors/#javascript-clients",
@@ -2672,13 +3617,13 @@
},
{
"location": "/topics/html-and-forms/",
- "text": "HTML \n Forms\n\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.\n\n\nRendering HTML\n\n\nIn order to return HTML responses you'll need to either \nTemplateHTMLRenderer\n, or \nStaticHTMLRenderer\n.\n\n\nThe \nTemplateHTMLRenderer\n class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.\n\n\nThe \nStaticHTMLRender\n class expects the response to contain a string of the pre-rendered HTML content.\n\n\nBecause static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.\n\n\nHere's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:\n\n\nviews.py\n:\n\n\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset})\n\n\n\nprofile_list.html\n:\n\n\nhtml\nbody\n\n\nh1\nProfiles\n/h1\n\n\nul\n\n {% for profile in profiles %}\n \nli\n{{ profile.name }}\n/li\n\n {% endfor %}\n\n/ul\n\n\n/body\n/html\n\n\n\n\nRendering Forms\n\n\nSerializers may be rendered as forms by using the \nrender_form\n template tag, and including the serializer instance as context to the template.\n\n\nThe following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:\n\n\nviews.py\n:\n\n\nfrom django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile, data=request.data)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n serializer.save()\n return redirect('profile-list')\n\n\n\nprofile_detail.html\n:\n\n\n{% load rest_framework %}\n\n\nhtml\nbody\n\n\n\nh1\nProfile - {{ profile.name }}\n/h1\n\n\n\nform action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\"\n\n {% csrf_token %}\n {% render_form serializer %}\n \ninput type=\"submit\" value=\"Save\"\n\n\n/form\n\n\n\n/body\n/html\n\n\n\n\nUsing template packs\n\n\nThe \nrender_form\n tag takes an optional \ntemplate_pack\n argument, that specifies which template directory should be used for rendering the form and form fields.\n\n\nREST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are \nhorizontal\n, \nvertical\n, and \ninline\n. The default style is \nhorizontal\n. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.\n\n\nThe following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:\n\n\nhead\n\n \u2026\n \nlink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\"\n\n\n/head\n\n\n\n\nThird party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.\n\n\nLet's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.\n\n\nclass LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email'}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField()\n\n\n\n\n\nrest_framework/vertical\n\n\nPresents form labels above their corresponding control inputs, using the standard Bootstrap layout.\n\n\nThis is the default template pack.\n\n\n{% load rest_framework %}\n\n...\n\n\nform action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/horizontal\n\n\nPresents labels and controls alongside each other, using a 2/10 column split.\n\n\nThis is the form style used in the browsable API and admin renderers.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer %}\n \ndiv class=\"form-group\"\n\n \ndiv class=\"col-sm-offset-2 col-sm-10\"\n\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n \n/div\n\n \n/div\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/inline\n\n\nA compact form style that presents all the controls inline.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\nField styles\n\n\nSerializer fields can have their rendering style customized by using the \nstyle\n keyword argument. This argument is a dictionary of options that control the template and layout used.\n\n\nThe most common way to customize the field style is to use the \nbase_template\n style keyword argument to select which template in the template pack should be use.\n\n\nFor example, to render a \nCharField\n as an HTML textarea rather than the default HTML input, you would use something like this:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n)\n\n\n\nIf you instead want a field to be rendered using a custom template that is \nnot part of an included template pack\n, you can instead use the \ntemplate\n style option, to fully specify a template name:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n)\n\n\n\nField templates can also use additional style properties, depending on their type. For example, the \ntextarea.html\n template also accepts a \nrows\n property that can be used to affect the sizing of the control.\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n)\n\n\n\nThe complete list of \nbase_template\n options and their associated style options is listed below.\n\n\n\n\n\n\n\n\nbase_template\n\n\nValid field types\n\n\nAdditional style options\n\n\n\n\n\n\n\n\n\n\ninput.html\n\n\nAny string, numeric or date/time field\n\n\ninput_type, placeholder, hide_label\n\n\n\n\n\n\ntextarea.html\n\n\nCharField\n\n\nrows, placeholder, hide_label\n\n\n\n\n\n\nselect.html\n\n\nChoiceField\n or relational field types\n\n\nhide_label\n\n\n\n\n\n\nradio.html\n\n\nChoiceField\n or relational field types\n\n\ninline, hide_label\n\n\n\n\n\n\nselect_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\nhide_label\n\n\n\n\n\n\ncheckbox_multiple.html\n\n\nMultipleChoiceField\n or relational fields with \nmany=True\n\n\ninline, hide_label\n\n\n\n\n\n\ncheckbox.html\n\n\nBooleanField\n\n\nhide_label\n\n\n\n\n\n\nfieldset.html\n\n\nNested serializer\n\n\nhide_label\n\n\n\n\n\n\nlist_fieldset.html\n\n\nListField\n or nested serializer with \nmany=True\n\n\nhide_label",
+ "text": "HTML \n Forms\n\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.\n\n\nRendering HTML\n\n\nIn order to return HTML responses you'll need to either \nTemplateHTMLRenderer\n, or \nStaticHTMLRenderer\n.\n\n\nThe \nTemplateHTMLRenderer\n class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.\n\n\nThe \nStaticHTMLRender\n class expects the response to contain a string of the pre-rendered HTML content.\n\n\nBecause static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.\n\n\nHere's an example of a view that returns a list of \"Profile\" instances, rendered in an HTML template:\n\n\nviews.py\n:\n\n\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ProfileList(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_list.html'\n\n def get(self, request):\n queryset = Profile.objects.all()\n return Response({'profiles': queryset})\n\n\n\nprofile_list.html\n:\n\n\nhtml\nbody\n\n\nh1\nProfiles\n/h1\n\n\nul\n\n {% for profile in profiles %}\n \nli\n{{ profile.name }}\n/li\n\n {% endfor %}\n\n/ul\n\n\n/body\n/html\n\n\n\n\nRendering Forms\n\n\nSerializers may be rendered as forms by using the \nrender_form\n template tag, and including the serializer instance as context to the template.\n\n\nThe following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:\n\n\nviews.py\n:\n\n\nfrom django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile, data=request.data)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n serializer.save()\n return redirect('profile-list')\n\n\n\nprofile_detail.html\n:\n\n\n{% load rest_framework %}\n\n\nhtml\nbody\n\n\n\nh1\nProfile - {{ profile.name }}\n/h1\n\n\n\nform action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\"\n\n {% csrf_token %}\n {% render_form serializer %}\n \ninput type=\"submit\" value=\"Save\"\n\n\n/form\n\n\n\n/body\n/html\n\n\n\n\nUsing template packs\n\n\nThe \nrender_form\n tag takes an optional \ntemplate_pack\n argument, that specifies which template directory should be used for rendering the form and form fields.\n\n\nREST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are \nhorizontal\n, \nvertical\n, and \ninline\n. The default style is \nhorizontal\n. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.\n\n\nThe following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:\n\n\nhead\n\n \u2026\n \nlink rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\"\n\n\n/head\n\n\n\n\nThird party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.\n\n\nLet's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form.\n\n\nclass LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email'}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField()\n\n\n\n\n\nrest_framework/vertical\n\n\nPresents form labels above their corresponding control inputs, using the standard Bootstrap layout.\n\n\nThis is the default template pack.\n\n\n{% load rest_framework %}\n\n...\n\n\nform action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/horizontal\n\n\nPresents labels and controls alongside each other, using a 2/10 column split.\n\n\nThis is the form style used in the browsable API and admin renderers.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer %}\n \ndiv class=\"form-group\"\n\n \ndiv class=\"col-sm-offset-2 col-sm-10\"\n\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n \n/div\n\n \n/div\n\n\n/form\n\n\n\n\n\n\n\n\nrest_framework/inline\n\n\nA compact form style that presents all the controls inline.\n\n\n{% load rest_framework %}\n\n...\n\n\nform class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate\n\n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n \nbutton type=\"submit\" class=\"btn btn-default\"\nSign in\n/button\n\n\n/form\n\n\n\n\n\n\nField styles\n\n\nSerializer fields can have their rendering style customized by using the \nstyle\n keyword argument. This argument is a dictionary of options that control the template and layout used.\n\n\nThe most common way to customize the field style is to use the \nbase_template\n style keyword argument to select which template in the template pack should be use.\n\n\nFor example, to render a \nCharField\n as an HTML textarea rather than the default HTML input, you would use something like this:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n)\n\n\n\nIf you instead want a field to be rendered using a custom template that is \nnot part of an included template pack\n, you can instead use the \ntemplate\n style option, to fully specify a template name:\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n)\n\n\n\nField templates can also use additional style properties, depending on their type. For example, the \ntextarea.html\n template also accepts a \nrows\n property that can be used to affect the sizing of the control.\n\n\ndetails = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n)\n\n\n\nThe complete list of \nbase_template\n options and their associated style options is listed below.\n\n\n\n\n\n\n\n\nbase_template\n\n\nValid field types\n\n\nAdditional style options\n\n\n\n\n\n\n\n\n\n\ninput.html\n\n\nAny string, numeric or date/time field\n\n\ninput_type, placeholder, hide_label\n\n\n\n\n\n\ntextarea.html\n\n\nCharField\n\n\nrows, placeholder, hide_label\n\n\n\n\n\n\nselect.html\n\n\nChoiceField\nor relational field types\n\n\nhide_label\n\n\n\n\n\n\nradio.html\n\n\nChoiceField\nor relational field types\n\n\ninline, hide_label\n\n\n\n\n\n\nselect_multiple.html\n\n\nMultipleChoiceField\nor relational fields with \nmany=True\n\n\nhide_label\n\n\n\n\n\n\ncheckbox_multiple.html\n\n\nMultipleChoiceField\nor relational fields with \nmany=True\n\n\ninline, hide_label\n\n\n\n\n\n\ncheckbox.html\n\n\nBooleanField\n\n\nhide_label\n\n\n\n\n\n\nfieldset.html\n\n\nNested serializer\n\n\nhide_label\n\n\n\n\n\n\nlist_fieldset.html\n\n\nListField\nor nested serializer with \nmany=True\n\n\nhide_label",
"title": "HTML & Forms"
},
{
"location": "/topics/html-and-forms/#html-forms",
"text": "REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.",
- "title": "HTML Forms"
+ "title": "HTML & Forms"
},
{
"location": "/topics/html-and-forms/#rendering-html",
@@ -2687,12 +3632,32 @@
},
{
"location": "/topics/html-and-forms/#rendering-forms",
- "text": "Serializers may be rendered as forms by using the render_form template tag, and including the serializer instance as context to the template. The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance: views.py : from django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile, data=request.data)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n serializer.save()\n return redirect('profile-list') profile_detail.html : {% load rest_framework %} html body h1 Profile - {{ profile.name }} /h1 form action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\" \n {% csrf_token %}\n {% render_form serializer %}\n input type=\"submit\" value=\"Save\" /form /body /html Using template packs The render_form tag takes an optional template_pack argument, that specifies which template directory should be used for rendering the form and form fields. REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are horizontal , vertical , and inline . The default style is horizontal . To use any of these template packs you'll want to also include the Bootstrap 3 CSS. The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS: head \n \u2026\n link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" /head Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates. Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form. class LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email'}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField() rest_framework/vertical Presents form labels above their corresponding control inputs, using the standard Bootstrap layout. This is the default template pack. {% load rest_framework %}\n\n... form action=\"{% url 'login' %}\" method=\"post\" novalidate \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n button type=\"submit\" class=\"btn btn-default\" Sign in /button /form rest_framework/horizontal Presents labels and controls alongside each other, using a 2/10 column split. This is the form style used in the browsable API and admin renderers. {% load rest_framework %}\n\n... form class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate \n {% csrf_token %}\n {% render_form serializer %}\n div class=\"form-group\" \n div class=\"col-sm-offset-2 col-sm-10\" \n button type=\"submit\" class=\"btn btn-default\" Sign in /button \n /div \n /div /form rest_framework/inline A compact form style that presents all the controls inline. {% load rest_framework %}\n\n... form class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n button type=\"submit\" class=\"btn btn-default\" Sign in /button /form",
+ "text": "Serializers may be rendered as forms by using the render_form template tag, and including the serializer instance as context to the template. The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance: views.py : from django.shortcuts import get_object_or_404\nfrom my_project.example.models import Profile\nfrom rest_framework.renderers import TemplateHTMLRenderer\nfrom rest_framework.views import APIView\n\n\nclass ProfileDetail(APIView):\n renderer_classes = [TemplateHTMLRenderer]\n template_name = 'profile_detail.html'\n\n def get(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile)\n return Response({'serializer': serializer, 'profile': profile})\n\n def post(self, request, pk):\n profile = get_object_or_404(Profile, pk=pk)\n serializer = ProfileSerializer(profile, data=request.data)\n if not serializer.is_valid():\n return Response({'serializer': serializer, 'profile': profile})\n serializer.save()\n return redirect('profile-list') profile_detail.html : {% load rest_framework %} html body h1 Profile - {{ profile.name }} /h1 form action=\"{% url 'profile-detail' pk=profile.pk %}\" method=\"POST\" \n {% csrf_token %}\n {% render_form serializer %}\n input type=\"submit\" value=\"Save\" /form /body /html",
"title": "Rendering Forms"
},
+ {
+ "location": "/topics/html-and-forms/#using-template-packs",
+ "text": "The render_form tag takes an optional template_pack argument, that specifies which template directory should be used for rendering the form and form fields. REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are horizontal , vertical , and inline . The default style is horizontal . To use any of these template packs you'll want to also include the Bootstrap 3 CSS. The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS: head \n \u2026\n link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" /head Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates. Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a \"Login\" form. class LoginSerializer(serializers.Serializer):\n email = serializers.EmailField(\n max_length=100,\n style={'placeholder': 'Email'}\n )\n password = serializers.CharField(\n max_length=100,\n style={'input_type': 'password', 'placeholder': 'Password'}\n )\n remember_me = serializers.BooleanField()",
+ "title": "Using template packs"
+ },
+ {
+ "location": "/topics/html-and-forms/#rest_frameworkvertical",
+ "text": "Presents form labels above their corresponding control inputs, using the standard Bootstrap layout. This is the default template pack. {% load rest_framework %}\n\n... form action=\"{% url 'login' %}\" method=\"post\" novalidate \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/vertical' %}\n button type=\"submit\" class=\"btn btn-default\" Sign in /button /form",
+ "title": "rest_framework/vertical"
+ },
+ {
+ "location": "/topics/html-and-forms/#rest_frameworkhorizontal",
+ "text": "Presents labels and controls alongside each other, using a 2/10 column split. This is the form style used in the browsable API and admin renderers. {% load rest_framework %}\n\n... form class=\"form-horizontal\" action=\"{% url 'login' %}\" method=\"post\" novalidate \n {% csrf_token %}\n {% render_form serializer %}\n div class=\"form-group\" \n div class=\"col-sm-offset-2 col-sm-10\" \n button type=\"submit\" class=\"btn btn-default\" Sign in /button \n /div \n /div /form",
+ "title": "rest_framework/horizontal"
+ },
+ {
+ "location": "/topics/html-and-forms/#rest_frameworkinline",
+ "text": "A compact form style that presents all the controls inline. {% load rest_framework %}\n\n... form class=\"form-inline\" action=\"{% url 'login' %}\" method=\"post\" novalidate \n {% csrf_token %}\n {% render_form serializer template_pack='rest_framework/inline' %}\n button type=\"submit\" class=\"btn btn-default\" Sign in /button /form",
+ "title": "rest_framework/inline"
+ },
{
"location": "/topics/html-and-forms/#field-styles",
- "text": "Serializer fields can have their rendering style customized by using the style keyword argument. This argument is a dictionary of options that control the template and layout used. The most common way to customize the field style is to use the base_template style keyword argument to select which template in the template pack should be use. For example, to render a CharField as an HTML textarea rather than the default HTML input, you would use something like this: details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n) If you instead want a field to be rendered using a custom template that is not part of an included template pack , you can instead use the template style option, to fully specify a template name: details = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n) Field templates can also use additional style properties, depending on their type. For example, the textarea.html template also accepts a rows property that can be used to affect the sizing of the control. details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n) The complete list of base_template options and their associated style options is listed below. base_template Valid field types Additional style options input.html Any string, numeric or date/time field input_type, placeholder, hide_label textarea.html CharField rows, placeholder, hide_label select.html ChoiceField or relational field types hide_label radio.html ChoiceField or relational field types inline, hide_label select_multiple.html MultipleChoiceField or relational fields with many=True hide_label checkbox_multiple.html MultipleChoiceField or relational fields with many=True inline, hide_label checkbox.html BooleanField hide_label fieldset.html Nested serializer hide_label list_fieldset.html ListField or nested serializer with many=True hide_label",
+ "text": "Serializer fields can have their rendering style customized by using the style keyword argument. This argument is a dictionary of options that control the template and layout used. The most common way to customize the field style is to use the base_template style keyword argument to select which template in the template pack should be use. For example, to render a CharField as an HTML textarea rather than the default HTML input, you would use something like this: details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html'}\n) If you instead want a field to be rendered using a custom template that is not part of an included template pack , you can instead use the template style option, to fully specify a template name: details = serializers.CharField(\n max_length=1000,\n style={'template': 'my-field-templates/custom-input.html'}\n) Field templates can also use additional style properties, depending on their type. For example, the textarea.html template also accepts a rows property that can be used to affect the sizing of the control. details = serializers.CharField(\n max_length=1000,\n style={'base_template': 'textarea.html', 'rows': 10}\n) The complete list of base_template options and their associated style options is listed below. base_template Valid field types Additional style options input.html Any string, numeric or date/time field input_type, placeholder, hide_label textarea.html CharField rows, placeholder, hide_label select.html ChoiceField or relational field types hide_label radio.html ChoiceField or relational field types inline, hide_label select_multiple.html MultipleChoiceField or relational fields with many=True hide_label checkbox_multiple.html MultipleChoiceField or relational fields with many=True inline, hide_label checkbox.html BooleanField hide_label fieldset.html Nested serializer hide_label list_fieldset.html ListField or nested serializer with many=True hide_label",
"title": "Field styles"
},
{
@@ -2757,9 +3722,59 @@
},
{
"location": "/topics/browsable-api/#customizing",
- "text": "The browsable API is built with Twitter's Bootstrap (v 3.3.5), making it easy to customize the look-and-feel. To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html . For example: templates/rest_framework/api.html {% extends \"rest_framework/base.html\" %}\n\n... # Override blocks with required customizations Overriding the default theme To replace the default theme, add a bootstrap_theme block to your api.html and insert a link to the desired Bootstrap theme css file. This will completely replace the included theme. {% block bootstrap_theme %}\n link rel=\"stylesheet\" href=\"/path/to/my/bootstrap.css\" type=\"text/css\" \n{% endblock %} Suitable pre-made replacement themes are available at Bootswatch . To use any of the Bootswatch themes, simply download the theme's bootstrap.min.css file, add it to your project, and replace the default one as described above. You can also change the navbar variant, which by default is navbar-inverse , using the bootstrap_navbar_variant block. The empty {% block bootstrap_navbar_variant %}{% endblock %} will use the original Bootstrap navbar style. Full example: {% extends \"rest_framework/base.html\" %}\n\n{% block bootstrap_theme %}\n link rel=\"stylesheet\" href=\"http://bootswatch.com/flatly/bootstrap.min.css\" type=\"text/css\" \n{% endblock %}\n\n{% block bootstrap_navbar_variant %}{% endblock %} For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block. Screenshot of the bootswatch 'Cerulean' theme Screenshot of the bootswatch 'Slate' theme Blocks All of the blocks available in the browsable API base template that can be used in your api.html . body - The entire html body . bodyclass - Class attribute for the body tag, empty by default. bootstrap_theme - CSS for the Bootstrap theme. bootstrap_navbar_variant - CSS class for the navbar. branding - Branding section of the navbar, see Bootstrap components . breadcrumbs - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block. script - JavaScript files for the page. style - CSS stylesheets for the page. title - Title of the page. userlinks - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links. Components All of the standard Bootstrap components are available. Tooltips The browsable API makes use of the Bootstrap tooltips component. Any element with the js-tooltip class and a title attribute has that title content will display a tooltip on hover events. Login Template To add branding and customize the look-and-feel of the login template, create a template called login.html and add it to your project, eg: templates/rest_framework/login.html . The template should extend from rest_framework/login_base.html . You can add your site name or branding by including the branding block: {% block branding %}\n h3 style=\"margin: 0 0 20px;\" My Site Name /h3 \n{% endblock %} You can also customize the style by adding the bootstrap_theme or style block similar to api.html . Advanced Customization Context The context that's available to the template: allowed_methods : A list of methods allowed by the resource api_settings : The API settings available_formats : A list of formats allowed by the resource breadcrumblist : The list of links following the chain of nested resources content : The content of the API response description : The description of the resource, generated from its docstring name : The name of the resource post_form : A form instance for use by the POST form (if allowed) put_form : A form instance for use by the PUT form (if allowed) display_edit_forms : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed request : The request object response : The response object version : The version of Django REST Framework view : The view handling the request FORMAT_PARAM : The view can accept a format override METHOD_PARAM : The view can accept a method override You can override the BrowsableAPIRenderer.get_context() method to customise the context that gets passed to the template. Not using base.html 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 api.html extend base.html . Then the page content and capabilities are entirely up to you. Handling ChoiceField with large numbers of items. When a relationship or ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. The simplest option in this case is to replace the select input with a standard text input. For example: author = serializers.HyperlinkedRelatedField(\n queryset=User.objects.all(),\n style={'base_template': 'input.html'}\n) Autocomplete 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. There are a variety of packages for autocomplete widgets , such as django-autocomplete-light , 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 widget keyword argument since it now uses templated HTML generation. Better support for autocomplete inputs is planned in future versions.",
+ "text": "The browsable API is built with Twitter's Bootstrap (v 3.3.5), making it easy to customize the look-and-feel. To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html . For example: templates/rest_framework/api.html {% extends \"rest_framework/base.html\" %}\n\n... # Override blocks with required customizations",
"title": "Customizing"
},
+ {
+ "location": "/topics/browsable-api/#overriding-the-default-theme",
+ "text": "To replace the default theme, add a bootstrap_theme block to your api.html and insert a link to the desired Bootstrap theme css file. This will completely replace the included theme. {% block bootstrap_theme %}\n link rel=\"stylesheet\" href=\"/path/to/my/bootstrap.css\" type=\"text/css\" \n{% endblock %} Suitable pre-made replacement themes are available at Bootswatch . To use any of the Bootswatch themes, simply download the theme's bootstrap.min.css file, add it to your project, and replace the default one as described above. You can also change the navbar variant, which by default is navbar-inverse , using the bootstrap_navbar_variant block. The empty {% block bootstrap_navbar_variant %}{% endblock %} will use the original Bootstrap navbar style. Full example: {% extends \"rest_framework/base.html\" %}\n\n{% block bootstrap_theme %}\n link rel=\"stylesheet\" href=\"http://bootswatch.com/flatly/bootstrap.min.css\" type=\"text/css\" \n{% endblock %}\n\n{% block bootstrap_navbar_variant %}{% endblock %} For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block. Screenshot of the bootswatch 'Cerulean' theme Screenshot of the bootswatch 'Slate' theme",
+ "title": "Overriding the default theme"
+ },
+ {
+ "location": "/topics/browsable-api/#blocks",
+ "text": "All of the blocks available in the browsable API base template that can be used in your api.html . body - The entire html body . bodyclass - Class attribute for the body tag, empty by default. bootstrap_theme - CSS for the Bootstrap theme. bootstrap_navbar_variant - CSS class for the navbar. branding - Branding section of the navbar, see Bootstrap components . breadcrumbs - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block. script - JavaScript files for the page. style - CSS stylesheets for the page. title - Title of the page. userlinks - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.",
+ "title": "Blocks"
+ },
+ {
+ "location": "/topics/browsable-api/#components",
+ "text": "All of the standard Bootstrap components are available.",
+ "title": "Components"
+ },
+ {
+ "location": "/topics/browsable-api/#tooltips",
+ "text": "The browsable API makes use of the Bootstrap tooltips component. Any element with the js-tooltip class and a title attribute has that title content will display a tooltip on hover events.",
+ "title": "Tooltips"
+ },
+ {
+ "location": "/topics/browsable-api/#login-template",
+ "text": "To add branding and customize the look-and-feel of the login template, create a template called login.html and add it to your project, eg: templates/rest_framework/login.html . The template should extend from rest_framework/login_base.html . You can add your site name or branding by including the branding block: {% block branding %}\n h3 style=\"margin: 0 0 20px;\" My Site Name /h3 \n{% endblock %} You can also customize the style by adding the bootstrap_theme or style block similar to api.html .",
+ "title": "Login Template"
+ },
+ {
+ "location": "/topics/browsable-api/#advanced-customization",
+ "text": "",
+ "title": "Advanced Customization"
+ },
+ {
+ "location": "/topics/browsable-api/#context",
+ "text": "The context that's available to the template: allowed_methods : A list of methods allowed by the resource api_settings : The API settings available_formats : A list of formats allowed by the resource breadcrumblist : The list of links following the chain of nested resources content : The content of the API response description : The description of the resource, generated from its docstring name : The name of the resource post_form : A form instance for use by the POST form (if allowed) put_form : A form instance for use by the PUT form (if allowed) display_edit_forms : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed request : The request object response : The response object version : The version of Django REST Framework view : The view handling the request FORMAT_PARAM : The view can accept a format override METHOD_PARAM : The view can accept a method override You can override the BrowsableAPIRenderer.get_context() method to customise the context that gets passed to the template.",
+ "title": "Context"
+ },
+ {
+ "location": "/topics/browsable-api/#not-using-basehtml",
+ "text": "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 api.html extend base.html . Then the page content and capabilities are entirely up to you.",
+ "title": "Not using base.html"
+ },
+ {
+ "location": "/topics/browsable-api/#handling-choicefield-with-large-numbers-of-items",
+ "text": "When a relationship or ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. The simplest option in this case is to replace the select input with a standard text input. For example: author = serializers.HyperlinkedRelatedField(\n queryset=User.objects.all(),\n style={'base_template': 'input.html'}\n)",
+ "title": "Handling ChoiceField with large numbers of items."
+ },
+ {
+ "location": "/topics/browsable-api/#autocomplete",
+ "text": "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. There are a variety of packages for autocomplete widgets , such as django-autocomplete-light , 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 widget keyword argument since it now uses templated HTML generation. Better support for autocomplete inputs is planned in future versions.",
+ "title": "Autocomplete"
+ },
{
"location": "/topics/rest-hypermedia-hateoas/",
"text": "REST, Hypermedia \n HATEOAS\n\n\n\n\nYou keep using that word \"REST\". I do not think it means what you think it means.\n\n\n Mike Amundsen, \nREST fest 2012 keynote\n.\n\n\n\n\nFirst 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\".\n\n\nIf you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.\n\n\nThe following fall into the \"required reading\" category.\n\n\n\n\nRoy Fielding's dissertation - \nArchitectural Styles and\nthe Design of Network-based Software Architectures\n.\n\n\nRoy Fielding's \"\nREST APIs must be hypertext-driven\n\" blog post.\n\n\nLeonard Richardson \n Mike Amundsen's \nRESTful Web APIs\n.\n\n\nMike Amundsen's \nBuilding Hypermedia APIs with HTML5 and Node\n.\n\n\nSteve Klabnik's \nDesigning Hypermedia APIs\n.\n\n\nThe \nRichardson Maturity Model\n.\n\n\n\n\nFor a more thorough background, check out Klabnik's \nHypermedia API reading list\n.\n\n\nBuilding Hypermedia APIs with REST framework\n\n\nREST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.\n\n\nWhat REST framework provides.\n\n\nIt 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.\n\n\nREST framework also includes \nserialization\n and \nparser\n/\nrenderer\n components that make it easy to build appropriate media types, \nhyperlinked relations\n for building well-connected systems, and great support for \ncontent negotiation\n.\n\n\nWhat REST framework doesn't provide.\n\n\nWhat REST framework doesn't do is give you machine readable hypermedia formats such as \nHAL\n, \nCollection+JSON\n, \nJSON API\n or HTML \nmicroformats\n 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.",
@@ -2768,7 +3783,7 @@
{
"location": "/topics/rest-hypermedia-hateoas/#rest-hypermedia-hateoas",
"text": "You keep using that word \"REST\". I do not think it means what you think it means. Mike Amundsen, REST fest 2012 keynote . 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\". If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices. The following fall into the \"required reading\" category. Roy Fielding's dissertation - Architectural Styles and\nthe Design of Network-based Software Architectures . Roy Fielding's \" REST APIs must be hypertext-driven \" blog post. Leonard Richardson Mike Amundsen's RESTful Web APIs . Mike Amundsen's Building Hypermedia APIs with HTML5 and Node . Steve Klabnik's Designing Hypermedia APIs . The Richardson Maturity Model . For a more thorough background, check out Klabnik's Hypermedia API reading list .",
- "title": "REST, Hypermedia HATEOAS"
+ "title": "REST, Hypermedia & HATEOAS"
},
{
"location": "/topics/rest-hypermedia-hateoas/#building-hypermedia-apis-with-rest-framework",
@@ -2787,7 +3802,7 @@
},
{
"location": "/topics/third-party-resources/",
- "text": "Third Party Resources\n\n\n\n\nSoftware ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.\n\n\n \nJan Bosch\n.\n\n\n\n\nAbout Third Party Packages\n\n\nThird Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.\n\n\nWe \nsupport\n, \nencourage\n and \nstrongly favor\n the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.\n\n\nWe aim to make creating third party packages as easy as possible, whilst keeping a \nsimple\n and \nwell maintained\n 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.\n\n\nIf 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 \nMailing List\n.\n\n\nHow to create a Third Party Package\n\n\nCreating your package\n\n\nYou can use \nthis cookiecutter template\n 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.\n\n\nNote: Let us know if you have an alternate cookiecuter package so we can also link to it.\n\n\nRunning the initial cookiecutter command\n\n\nTo run the initial cookiecutter command, you'll first need to install the Python \ncookiecutter\n package.\n\n\n$ pip install cookiecutter\n\n\n\nOnce \ncookiecutter\n is installed just run the following to create a new project.\n\n\n$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework\n\n\n\nYou'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.\n\n\nfull_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")?\n\n\n\nGetting it onto GitHub\n\n\nTo put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository \nhere\n. If you need help, check out the \nCreate A Repo\n article on GitHub.\n\n\nAdding to Travis CI\n\n\nWe recommend using \nTravis CI\n, a hosted continuous integration service which integrates well with GitHub and is free for public repositories.\n\n\nTo get started with Travis CI, \nsign in\n with your GitHub account. Once you're signed in, go to your \nprofile page\n and enable the service hook for the repository you want.\n\n\nIf you use the cookiecutter template, your project will already contain a \n.travis.yml\n file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.\n\n\nUploading to PyPI\n\n\nOnce you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via \npip\n.\n\n\nYou must \nregister\n an account before publishing to PyPI.\n\n\nTo register your package on PyPI run the following command.\n\n\n$ python setup.py register\n\n\n\nIf this is the first time publishing to PyPI, you'll be prompted to login.\n\n\nNote: Before publishing you'll need to make sure you have the latest pip that supports \nwheel\n as well as install the \nwheel\n package.\n\n\n$ pip install --upgrade pip\n$ pip install wheel\n\n\n\nAfter this, every time you want to release a new version on PyPI just run the following command.\n\n\n$ python setup.py publish\nYou probably want to also tag the version now:\n git tag -a {0} -m 'version 0.1.0'\n git push --tags\n\n\n\nAfter releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.\n\n\nWe recommend to follow \nSemantic Versioning\n for your package's versions.\n\n\nDevelopment\n\n\nVersion requirements\n\n\nThe cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, \ntox.ini\n, \n.travis.yml\n, and \nsetup.py\n to match the set of versions you wish to support.\n\n\nTests\n\n\nThe cookiecutter template includes a \nruntests.py\n which uses the \npytest\n package as a test runner.\n\n\nBefore running, you'll need to install a couple test requirements.\n\n\n$ pip install -r requirements.txt\n\n\n\nOnce requirements installed, you can run \nruntests.py\n.\n\n\n$ ./runtests.py\n\n\n\nRun using a more concise output style.\n\n\n$ ./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n$ ./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n$ ./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n$ ./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n$ ./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n$ ./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n$ ./runtests.py test_this_method\n\n\n\nTo run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using \ntox\n. \nTox\n is a generic virtualenv management and test command line tool.\n\n\nFirst, install \ntox\n globally.\n\n\n$ pip install tox\n\n\n\nTo run \ntox\n, just simply run:\n\n\n$ tox\n\n\n\nTo run a particular \ntox\n environment:\n\n\n$ tox -e envlist\n\n\n\nenvlist\n is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:\n\n\n$ tox -l\n\n\n\nVersion compatibility\n\n\nSometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nCheck out Django REST framework's \ncompat.py\n for an example.\n\n\nOnce your package is available\n\n\nOnce your package is decently documented and available on PyPI, you might want share it with others that might find it useful.\n\n\nAdding to the Django REST framework grid\n\n\nWe suggest adding your package to the \nREST Framework\n grid on Django Packages.\n\n\nAdding to the Django REST framework docs\n\n\nCreate a \nPull Request\n or \nIssue\n on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under \nThird party packages\n of the API Guide section that best applies, like \nAuthentication\n or \nPermissions\n. You can also link your package under the \nThird Party Resources\n section.\n\n\nAnnounce on the discussion group.\n\n\nYou can also let others know about your package through the \ndiscussion group\n.\n\n\nExisting Third Party Packages\n\n\nDjango REST Framework has a growing community of developers, packages, and resources.\n\n\nCheck out a grid detailing all the packages and ecosystem around Django REST Framework at \nDjango Packages\n.\n\n\nTo submit new content, \nopen an issue\n or \ncreate a pull request\n.\n\n\nAuthentication\n\n\n\n\ndjangorestframework-digestauth\n - Provides Digest Access Authentication support.\n\n\ndjango-oauth-toolkit\n - Provides OAuth 2.0 support.\n\n\ndoac\n - Provides OAuth 2.0 support.\n\n\ndjangorestframework-jwt\n - Provides JSON Web Token Authentication support.\n\n\nhawkrest\n - Provides Hawk HTTP Authorization.\n\n\ndjangorestframework-httpsignature\n - Provides an easy to use HTTP Signature Authentication mechanism.\n\n\ndjoser\n - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.\n\n\ndjango-rest-auth\n - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.\n\n\n\n\nPermissions\n\n\n\n\ndrf-any-permissions\n - Provides alternative permission handling.\n\n\ndjangorestframework-composed-permissions\n - Provides a simple way to define complex permissions.\n\n\nrest_condition\n - Another extension for building complex permissions in a simple and convenient way.\n\n\ndry-rest-permissions\n - Provides a simple way to define permissions for individual api actions.\n\n\n\n\nSerializers\n\n\n\n\ndjango-rest-framework-mongoengine\n - Serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\ndjangorestframework-gis\n - Geographic add-ons\n\n\ndjangorestframework-hstore\n - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\nhtml-json-forms\n: Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.\n\n\n\n\nSerializer fields\n\n\n\n\ndrf-compound-fields\n - Provides \"compound\" serializer fields, such as lists of simple values.\n\n\ndjango-extra-fields\n - Provides extra serializer fields.\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\n\n\nViews\n\n\n\n\ndjangorestframework-bulk\n - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\ndjango-rest-multiple-models\n - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.\n\n\n\n\nRouters\n\n\n\n\ndrf-nested-routers\n - Provides routers and relationship fields for working with nested resources.\n\n\nwq.db.rest\n - Provides an admin-style model registration API with reasonable default URLs and viewsets.\n\n\n\n\nParsers\n\n\n\n\ndjangorestframework-msgpack\n - Provides MessagePack renderer and parser support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndjangorestframework-camel-case\n - Provides camel case JSON renderers and parsers.\n\n\n\n\nRenderers\n\n\n\n\ndjangorestframework-csv\n - Provides CSV renderer support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndrf_ujson\n - Implements JSON rendering using the UJSON package.\n\n\nrest-pandas\n - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.\n\n\n\n\nFiltering\n\n\n\n\ndjangorestframework-chain\n - Allows arbitrary chaining of both relations and lookup filters.\n\n\ndjango-url-filter\n - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.\n\n\n\n\nMisc\n\n\n\n\ncookiecutter-django-rest\n - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.\n\n\ndjangorestrelationalhyperlink\n - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.\n\n\ndjango-rest-swagger\n - An API documentation generator for Swagger UI.\n\n\ndjango-rest-framework-proxy\n - Proxy to redirect incoming request to another API server.\n\n\ngaiarestframework\n - Utils for django-rest-framework\n\n\ndrf-extensions\n - A collection of custom extensions\n\n\nember-django-adapter\n - An adapter for working with Ember.js\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\ndrf-tracking\n - Utilities to track requests to DRF API views.\n\n\ndjango-rest-framework-braces\n - Collection of utilities for working with Django Rest Framework. The most notable ones are \nFormSerializer\n and \nSerializerForm\n, which are adapters between DRF serializers and Django forms.\n\n\ndrf-haystack\n - Haystack search for Django Rest Framework\n\n\ndjango-rest-framework-version-transforms\n - Enables the use of delta transformations for versioning of DRF resource representations.\n\n\ndjango-rest-messaging\n, \ndjango-rest-messaging-centrifugo\n and \ndjango-rest-messaging-js\n - A real-time pluggable messaging service using DRM.\n\n\n\n\nOther Resources\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django Rest Framework\n\n\nGetting Started with Django Rest Framework and AngularJS\n\n\nEnd to end web app with Django-Rest-Framework \n AngularJS\n\n\nStart Your API - django-rest-framework part 1\n\n\nPermissions \n Authentication - django-rest-framework part 2\n\n\nViewSets and Routers - django-rest-framework part 3\n\n\nDjango Rest Framework User Endpoint\n\n\nCheck credentials using Django Rest Framework\n\n\n\n\nVideos\n\n\n\n\nEmber and Django Part 1 (Video)\n\n\nDjango Rest Framework Part 1 (Video)\n\n\nPyowa July 2013 - Django Rest Framework (Video)\n\n\ndjango-rest-framework and angularjs (Video)\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: profiling Django REST framework\n\n\nAPI Development with Django and Django REST Framework\n\n\nBlog posts about Django REST framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework",
+ "text": "Third Party Resources\n\n\n\n\nSoftware ecosystems [\u2026] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.\n\n\n \nJan Bosch\n.\n\n\n\n\nAbout Third Party Packages\n\n\nThird Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.\n\n\nWe \nsupport\n, \nencourage\n and \nstrongly favor\n the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.\n\n\nWe aim to make creating third party packages as easy as possible, whilst keeping a \nsimple\n and \nwell maintained\n 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.\n\n\nIf 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 \nMailing List\n.\n\n\nHow to create a Third Party Package\n\n\nCreating your package\n\n\nYou can use \nthis cookiecutter template\n 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.\n\n\nNote: Let us know if you have an alternate cookiecuter package so we can also link to it.\n\n\nRunning the initial cookiecutter command\n\n\nTo run the initial cookiecutter command, you'll first need to install the Python \ncookiecutter\n package.\n\n\n$ pip install cookiecutter\n\n\n\nOnce \ncookiecutter\n is installed just run the following to create a new project.\n\n\n$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework\n\n\n\nYou'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.\n\n\nfull_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")?\n\n\n\nGetting it onto GitHub\n\n\nTo put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository \nhere\n. If you need help, check out the \nCreate A Repo\n article on GitHub.\n\n\nAdding to Travis CI\n\n\nWe recommend using \nTravis CI\n, a hosted continuous integration service which integrates well with GitHub and is free for public repositories.\n\n\nTo get started with Travis CI, \nsign in\n with your GitHub account. Once you're signed in, go to your \nprofile page\n and enable the service hook for the repository you want.\n\n\nIf you use the cookiecutter template, your project will already contain a \n.travis.yml\n file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.\n\n\nUploading to PyPI\n\n\nOnce you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via \npip\n.\n\n\nYou must \nregister\n an account before publishing to PyPI.\n\n\nTo register your package on PyPI run the following command.\n\n\n$ python setup.py register\n\n\n\nIf this is the first time publishing to PyPI, you'll be prompted to login.\n\n\nNote: Before publishing you'll need to make sure you have the latest pip that supports \nwheel\n as well as install the \nwheel\n package.\n\n\n$ pip install --upgrade pip\n$ pip install wheel\n\n\n\nAfter this, every time you want to release a new version on PyPI just run the following command.\n\n\n$ python setup.py publish\nYou probably want to also tag the version now:\n git tag -a {0} -m 'version 0.1.0'\n git push --tags\n\n\n\nAfter releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.\n\n\nWe recommend to follow \nSemantic Versioning\n for your package's versions.\n\n\nDevelopment\n\n\nVersion requirements\n\n\nThe cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, \ntox.ini\n, \n.travis.yml\n, and \nsetup.py\n to match the set of versions you wish to support.\n\n\nTests\n\n\nThe cookiecutter template includes a \nruntests.py\n which uses the \npytest\n package as a test runner.\n\n\nBefore running, you'll need to install a couple test requirements.\n\n\n$ pip install -r requirements.txt\n\n\n\nOnce requirements installed, you can run \nruntests.py\n.\n\n\n$ ./runtests.py\n\n\n\nRun using a more concise output style.\n\n\n$ ./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n$ ./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n$ ./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n$ ./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n$ ./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n$ ./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n$ ./runtests.py test_this_method\n\n\n\nTo run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using \ntox\n. \nTox\n is a generic virtualenv management and test command line tool.\n\n\nFirst, install \ntox\n globally.\n\n\n$ pip install tox\n\n\n\nTo run \ntox\n, just simply run:\n\n\n$ tox\n\n\n\nTo run a particular \ntox\n environment:\n\n\n$ tox -e envlist\n\n\n\nenvlist\n is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:\n\n\n$ tox -l\n\n\n\nVersion compatibility\n\n\nSometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nCheck out Django REST framework's \ncompat.py\n for an example.\n\n\nOnce your package is available\n\n\nOnce your package is decently documented and available on PyPI, you might want share it with others that might find it useful.\n\n\nAdding to the Django REST framework grid\n\n\nWe suggest adding your package to the \nREST Framework\n grid on Django Packages.\n\n\nAdding to the Django REST framework docs\n\n\nCreate a \nPull Request\n or \nIssue\n on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under \nThird party packages\n of the API Guide section that best applies, like \nAuthentication\n or \nPermissions\n. You can also link your package under the \nThird Party Resources\n section.\n\n\nAnnounce on the discussion group.\n\n\nYou can also let others know about your package through the \ndiscussion group\n.\n\n\nExisting Third Party Packages\n\n\nDjango REST Framework has a growing community of developers, packages, and resources.\n\n\nCheck out a grid detailing all the packages and ecosystem around Django REST Framework at \nDjango Packages\n.\n\n\nTo submit new content, \nopen an issue\n or \ncreate a pull request\n.\n\n\nAuthentication\n\n\n\n\ndjangorestframework-digestauth\n - Provides Digest Access Authentication support.\n\n\ndjango-oauth-toolkit\n - Provides OAuth 2.0 support.\n\n\ndoac\n - Provides OAuth 2.0 support.\n\n\ndjangorestframework-jwt\n - Provides JSON Web Token Authentication support.\n\n\nhawkrest\n - Provides Hawk HTTP Authorization.\n\n\ndjangorestframework-httpsignature\n - Provides an easy to use HTTP Signature Authentication mechanism.\n\n\ndjoser\n - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.\n\n\ndjango-rest-auth\n - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.\n\n\n\n\nPermissions\n\n\n\n\ndrf-any-permissions\n - Provides alternative permission handling.\n\n\ndjangorestframework-composed-permissions\n - Provides a simple way to define complex permissions.\n\n\nrest_condition\n - Another extension for building complex permissions in a simple and convenient way.\n\n\ndry-rest-permissions\n - Provides a simple way to define permissions for individual api actions.\n\n\n\n\nSerializers\n\n\n\n\ndjango-rest-framework-mongoengine\n - Serializer class that supports using MongoDB as the storage layer for Django REST framework.\n\n\ndjangorestframework-gis\n - Geographic add-ons\n\n\ndjangorestframework-hstore\n - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\nhtml-json-forms\n: Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.\n\n\n\n\nSerializer fields\n\n\n\n\ndrf-compound-fields\n - Provides \"compound\" serializer fields, such as lists of simple values.\n\n\ndjango-extra-fields\n - Provides extra serializer fields.\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\n\n\nViews\n\n\n\n\ndjangorestframework-bulk\n - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\ndjango-rest-multiple-models\n - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.\n\n\n\n\nRouters\n\n\n\n\ndrf-nested-routers\n - Provides routers and relationship fields for working with nested resources.\n\n\nwq.db.rest\n - Provides an admin-style model registration API with reasonable default URLs and viewsets.\n\n\n\n\nParsers\n\n\n\n\ndjangorestframework-msgpack\n - Provides MessagePack renderer and parser support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndjangorestframework-camel-case\n - Provides camel case JSON renderers and parsers.\n\n\n\n\nRenderers\n\n\n\n\ndjangorestframework-csv\n - Provides CSV renderer support.\n\n\ndjangorestframework-jsonapi\n - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.\n\n\ndrf_ujson\n - Implements JSON rendering using the UJSON package.\n\n\nrest-pandas\n - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.\n\n\n\n\nFiltering\n\n\n\n\ndjangorestframework-chain\n - Allows arbitrary chaining of both relations and lookup filters.\n\n\ndjango-url-filter\n - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.\n\n\n\n\nMisc\n\n\n\n\ncookiecutter-django-rest\n - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.\n\n\ndjangorestrelationalhyperlink\n - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.\n\n\ndjango-rest-swagger\n - An API documentation generator for Swagger UI.\n\n\ndjango-rest-framework-proxy\n - Proxy to redirect incoming request to another API server.\n\n\ngaiarestframework\n - Utils for django-rest-framework\n\n\ndrf-extensions\n - A collection of custom extensions\n\n\nember-django-adapter\n - An adapter for working with Ember.js\n\n\ndjango-versatileimagefield\n - Provides a drop-in replacement for Django's stock \nImageField\n that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, \nclick here\n.\n\n\ndrf-tracking\n - Utilities to track requests to DRF API views.\n\n\ndjango-rest-framework-braces\n - Collection of utilities for working with Django Rest Framework. The most notable ones are \nFormSerializer\n and \nSerializerForm\n, which are adapters between DRF serializers and Django forms.\n\n\ndrf-haystack\n - Haystack search for Django Rest Framework\n\n\ndjango-rest-framework-version-transforms\n - Enables the use of delta transformations for versioning of DRF resource representations.\n\n\ndjango-rest-messaging\n, \ndjango-rest-messaging-centrifugo\n and \ndjango-rest-messaging-js\n - A real-time pluggable messaging service using DRM.\n\n\n\n\nOther Resources\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django Rest Framework\n\n\nGetting Started with Django Rest Framework and AngularJS\n\n\nEnd to end web app with Django-Rest-Framework \n AngularJS\n\n\nStart Your API - django-rest-framework part 1\n\n\nPermissions \n Authentication - django-rest-framework part 2\n\n\nViewSets and Routers - django-rest-framework part 3\n\n\nDjango Rest Framework User Endpoint\n\n\nCheck credentials using Django Rest Framework\n\n\nDjango REST Framework course\n\n\n\n\nVideos\n\n\n\n\nEmber and Django Part 1 (Video)\n\n\nDjango Rest Framework Part 1 (Video)\n\n\nPyowa July 2013 - Django Rest Framework (Video)\n\n\ndjango-rest-framework and angularjs (Video)\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: profiling Django REST framework\n\n\nAPI Development with Django and Django REST Framework\n\n\nBlog posts about Django REST framework\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework",
"title": "Third Party Resources"
},
{
@@ -2802,19 +3817,154 @@
},
{
"location": "/topics/third-party-resources/#how-to-create-a-third-party-package",
- "text": "Creating your package You can use this cookiecutter template 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. Note: Let us know if you have an alternate cookiecuter package so we can also link to it. Running the initial cookiecutter command To run the initial cookiecutter command, you'll first need to install the Python cookiecutter package. $ pip install cookiecutter Once cookiecutter is installed just run the following to create a new project. $ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework You'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values. full_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")? Getting it onto GitHub To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository here . If you need help, check out the Create A Repo article on GitHub. Adding to Travis CI We recommend using Travis CI , a hosted continuous integration service which integrates well with GitHub and is free for public repositories. To get started with Travis CI, sign in with your GitHub account. Once you're signed in, go to your profile page and enable the service hook for the repository you want. If you use the cookiecutter template, your project will already contain a .travis.yml file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request. Uploading to PyPI Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via pip . You must register an account before publishing to PyPI. To register your package on PyPI run the following command. $ python setup.py register If this is the first time publishing to PyPI, you'll be prompted to login. Note: Before publishing you'll need to make sure you have the latest pip that supports wheel as well as install the wheel package. $ pip install --upgrade pip\n$ pip install wheel After this, every time you want to release a new version on PyPI just run the following command. $ python setup.py publish\nYou probably want to also tag the version now:\n git tag -a {0} -m 'version 0.1.0'\n git push --tags After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release. We recommend to follow Semantic Versioning for your package's versions. Development Version requirements The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, tox.ini , .travis.yml , and setup.py to match the set of versions you wish to support. Tests The cookiecutter template includes a runtests.py which uses the pytest package as a test runner. Before running, you'll need to install a couple test requirements. $ pip install -r requirements.txt Once requirements installed, you can run runtests.py . $ ./runtests.py Run using a more concise output style. $ ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. $ ./runtests.py --fast Don't run the flake8 code linting. $ ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. $ ./runtests.py --lintonly Run the tests for a given test case. $ ./runtests.py MyTestCase Run the tests for a given test method. $ ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. $ ./runtests.py test_this_method To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using tox . Tox is a generic virtualenv management and test command line tool. First, install tox globally. $ pip install tox To run tox , just simply run: $ tox To run a particular tox environment: $ tox -e envlist envlist is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run: $ tox -l Version compatibility Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a compat.py module, and should provide a single common interface that the rest of the codebase can use. Check out Django REST framework's compat.py for an example. Once your package is available Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful. Adding to the Django REST framework grid We suggest adding your package to the REST Framework grid on Django Packages. Adding to the Django REST framework docs Create a Pull Request or Issue on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions . You can also link your package under the Third Party Resources section. Announce on the discussion group. You can also let others know about your package through the discussion group .",
+ "text": "",
"title": "How to create a Third Party Package"
},
+ {
+ "location": "/topics/third-party-resources/#creating-your-package",
+ "text": "You can use this cookiecutter template 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. Note: Let us know if you have an alternate cookiecuter package so we can also link to it.",
+ "title": "Creating your package"
+ },
+ {
+ "location": "/topics/third-party-resources/#running-the-initial-cookiecutter-command",
+ "text": "To run the initial cookiecutter command, you'll first need to install the Python cookiecutter package. $ pip install cookiecutter Once cookiecutter is installed just run the following to create a new project. $ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework You'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values. full_name (default is \"Your full name here\")? Johnny Appleseed\nemail (default is \"you@example.com\")? jappleseed@example.com\ngithub_username (default is \"yourname\")? jappleseed\npypi_project_name (default is \"dj-package\")? djangorestframework-custom-auth\nrepo_name (default is \"dj-package\")? django-rest-framework-custom-auth\napp_name (default is \"djpackage\")? custom_auth\nproject_short_description (default is \"Your project description goes here\")?\nyear (default is \"2014\")?\nversion (default is \"0.1.0\")?",
+ "title": "Running the initial cookiecutter command"
+ },
+ {
+ "location": "/topics/third-party-resources/#getting-it-onto-github",
+ "text": "To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository here . If you need help, check out the Create A Repo article on GitHub.",
+ "title": "Getting it onto GitHub"
+ },
+ {
+ "location": "/topics/third-party-resources/#adding-to-travis-ci",
+ "text": "We recommend using Travis CI , a hosted continuous integration service which integrates well with GitHub and is free for public repositories. To get started with Travis CI, sign in with your GitHub account. Once you're signed in, go to your profile page and enable the service hook for the repository you want. If you use the cookiecutter template, your project will already contain a .travis.yml file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.",
+ "title": "Adding to Travis CI"
+ },
+ {
+ "location": "/topics/third-party-resources/#uploading-to-pypi",
+ "text": "Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via pip . You must register an account before publishing to PyPI. To register your package on PyPI run the following command. $ python setup.py register If this is the first time publishing to PyPI, you'll be prompted to login. Note: Before publishing you'll need to make sure you have the latest pip that supports wheel as well as install the wheel package. $ pip install --upgrade pip\n$ pip install wheel After this, every time you want to release a new version on PyPI just run the following command. $ python setup.py publish\nYou probably want to also tag the version now:\n git tag -a {0} -m 'version 0.1.0'\n git push --tags After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release. We recommend to follow Semantic Versioning for your package's versions.",
+ "title": "Uploading to PyPI"
+ },
+ {
+ "location": "/topics/third-party-resources/#development",
+ "text": "",
+ "title": "Development"
+ },
+ {
+ "location": "/topics/third-party-resources/#version-requirements",
+ "text": "The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, tox.ini , .travis.yml , and setup.py to match the set of versions you wish to support.",
+ "title": "Version requirements"
+ },
+ {
+ "location": "/topics/third-party-resources/#tests",
+ "text": "The cookiecutter template includes a runtests.py which uses the pytest package as a test runner. Before running, you'll need to install a couple test requirements. $ pip install -r requirements.txt Once requirements installed, you can run runtests.py . $ ./runtests.py Run using a more concise output style. $ ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. $ ./runtests.py --fast Don't run the flake8 code linting. $ ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. $ ./runtests.py --lintonly Run the tests for a given test case. $ ./runtests.py MyTestCase Run the tests for a given test method. $ ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. $ ./runtests.py test_this_method To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using tox . Tox is a generic virtualenv management and test command line tool. First, install tox globally. $ pip install tox To run tox , just simply run: $ tox To run a particular tox environment: $ tox -e envlist envlist is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run: $ tox -l",
+ "title": "Tests"
+ },
+ {
+ "location": "/topics/third-party-resources/#version-compatibility",
+ "text": "Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a compat.py module, and should provide a single common interface that the rest of the codebase can use. Check out Django REST framework's compat.py for an example.",
+ "title": "Version compatibility"
+ },
+ {
+ "location": "/topics/third-party-resources/#once-your-package-is-available",
+ "text": "Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.",
+ "title": "Once your package is available"
+ },
+ {
+ "location": "/topics/third-party-resources/#adding-to-the-django-rest-framework-grid",
+ "text": "We suggest adding your package to the REST Framework grid on Django Packages.",
+ "title": "Adding to the Django REST framework grid"
+ },
+ {
+ "location": "/topics/third-party-resources/#adding-to-the-django-rest-framework-docs",
+ "text": "Create a Pull Request or Issue on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions . You can also link your package under the Third Party Resources section.",
+ "title": "Adding to the Django REST framework docs"
+ },
+ {
+ "location": "/topics/third-party-resources/#announce-on-the-discussion-group",
+ "text": "You can also let others know about your package through the discussion group .",
+ "title": "Announce on the discussion group."
+ },
{
"location": "/topics/third-party-resources/#existing-third-party-packages",
- "text": "Django REST Framework has a growing community of developers, packages, and resources. Check out a grid detailing all the packages and ecosystem around Django REST Framework at Django Packages . To submit new content, open an issue or create a pull request . Authentication djangorestframework-digestauth - Provides Digest Access Authentication support. django-oauth-toolkit - Provides OAuth 2.0 support. doac - Provides OAuth 2.0 support. djangorestframework-jwt - Provides JSON Web Token Authentication support. hawkrest - Provides Hawk HTTP Authorization. djangorestframework-httpsignature - Provides an easy to use HTTP Signature Authentication mechanism. djoser - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. django-rest-auth - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. Permissions drf-any-permissions - Provides alternative permission handling. djangorestframework-composed-permissions - Provides a simple way to define complex permissions. rest_condition - Another extension for building complex permissions in a simple and convenient way. dry-rest-permissions - Provides a simple way to define permissions for individual api actions. Serializers django-rest-framework-mongoengine - Serializer class that supports using MongoDB as the storage layer for Django REST framework. djangorestframework-gis - Geographic add-ons djangorestframework-hstore - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. html-json-forms : Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec. Serializer fields drf-compound-fields - Provides \"compound\" serializer fields, such as lists of simple values. django-extra-fields - Provides extra serializer fields. django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here . Views djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. django-rest-multiple-models - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request. Routers drf-nested-routers - Provides routers and relationship fields for working with nested resources. wq.db.rest - Provides an admin-style model registration API with reasonable default URLs and viewsets. Parsers djangorestframework-msgpack - Provides MessagePack renderer and parser support. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. djangorestframework-camel-case - Provides camel case JSON renderers and parsers. Renderers djangorestframework-csv - Provides CSV renderer support. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. drf_ujson - Implements JSON rendering using the UJSON package. rest-pandas - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats. Filtering djangorestframework-chain - Allows arbitrary chaining of both relations and lookup filters. django-url-filter - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF. Misc cookiecutter-django-rest - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome. djangorestrelationalhyperlink - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer. django-rest-swagger - An API documentation generator for Swagger UI. django-rest-framework-proxy - Proxy to redirect incoming request to another API server. gaiarestframework - Utils for django-rest-framework drf-extensions - A collection of custom extensions ember-django-adapter - An adapter for working with Ember.js django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here . drf-tracking - Utilities to track requests to DRF API views. django-rest-framework-braces - Collection of utilities for working with Django Rest Framework. The most notable ones are FormSerializer and SerializerForm , which are adapters between DRF serializers and Django forms. drf-haystack - Haystack search for Django Rest Framework django-rest-framework-version-transforms - Enables the use of delta transformations for versioning of DRF resource representations. django-rest-messaging , django-rest-messaging-centrifugo and django-rest-messaging-js - A real-time pluggable messaging service using DRM.",
+ "text": "Django REST Framework has a growing community of developers, packages, and resources. Check out a grid detailing all the packages and ecosystem around Django REST Framework at Django Packages . To submit new content, open an issue or create a pull request .",
"title": "Existing Third Party Packages"
},
+ {
+ "location": "/topics/third-party-resources/#authentication",
+ "text": "djangorestframework-digestauth - Provides Digest Access Authentication support. django-oauth-toolkit - Provides OAuth 2.0 support. doac - Provides OAuth 2.0 support. djangorestframework-jwt - Provides JSON Web Token Authentication support. hawkrest - Provides Hawk HTTP Authorization. djangorestframework-httpsignature - Provides an easy to use HTTP Signature Authentication mechanism. djoser - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. django-rest-auth - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.",
+ "title": "Authentication"
+ },
+ {
+ "location": "/topics/third-party-resources/#permissions",
+ "text": "drf-any-permissions - Provides alternative permission handling. djangorestframework-composed-permissions - Provides a simple way to define complex permissions. rest_condition - Another extension for building complex permissions in a simple and convenient way. dry-rest-permissions - Provides a simple way to define permissions for individual api actions.",
+ "title": "Permissions"
+ },
+ {
+ "location": "/topics/third-party-resources/#serializers",
+ "text": "django-rest-framework-mongoengine - Serializer class that supports using MongoDB as the storage layer for Django REST framework. djangorestframework-gis - Geographic add-ons djangorestframework-hstore - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. html-json-forms : Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec.",
+ "title": "Serializers"
+ },
+ {
+ "location": "/topics/third-party-resources/#serializer-fields",
+ "text": "drf-compound-fields - Provides \"compound\" serializer fields, such as lists of simple values. django-extra-fields - Provides extra serializer fields. django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here .",
+ "title": "Serializer fields"
+ },
+ {
+ "location": "/topics/third-party-resources/#views",
+ "text": "djangorestframework-bulk - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. django-rest-multiple-models - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.",
+ "title": "Views"
+ },
+ {
+ "location": "/topics/third-party-resources/#routers",
+ "text": "drf-nested-routers - Provides routers and relationship fields for working with nested resources. wq.db.rest - Provides an admin-style model registration API with reasonable default URLs and viewsets.",
+ "title": "Routers"
+ },
+ {
+ "location": "/topics/third-party-resources/#parsers",
+ "text": "djangorestframework-msgpack - Provides MessagePack renderer and parser support. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. djangorestframework-camel-case - Provides camel case JSON renderers and parsers.",
+ "title": "Parsers"
+ },
+ {
+ "location": "/topics/third-party-resources/#renderers",
+ "text": "djangorestframework-csv - Provides CSV renderer support. djangorestframework-jsonapi - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. drf_ujson - Implements JSON rendering using the UJSON package. rest-pandas - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.",
+ "title": "Renderers"
+ },
+ {
+ "location": "/topics/third-party-resources/#filtering",
+ "text": "djangorestframework-chain - Allows arbitrary chaining of both relations and lookup filters. django-url-filter - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.",
+ "title": "Filtering"
+ },
+ {
+ "location": "/topics/third-party-resources/#misc",
+ "text": "cookiecutter-django-rest - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome. djangorestrelationalhyperlink - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer. django-rest-swagger - An API documentation generator for Swagger UI. django-rest-framework-proxy - Proxy to redirect incoming request to another API server. gaiarestframework - Utils for django-rest-framework drf-extensions - A collection of custom extensions ember-django-adapter - An adapter for working with Ember.js django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here . drf-tracking - Utilities to track requests to DRF API views. django-rest-framework-braces - Collection of utilities for working with Django Rest Framework. The most notable ones are FormSerializer and SerializerForm , which are adapters between DRF serializers and Django forms. drf-haystack - Haystack search for Django Rest Framework django-rest-framework-version-transforms - Enables the use of delta transformations for versioning of DRF resource representations. django-rest-messaging , django-rest-messaging-centrifugo and django-rest-messaging-js - A real-time pluggable messaging service using DRM.",
+ "title": "Misc"
+ },
{
"location": "/topics/third-party-resources/#other-resources",
- "text": "Tutorials Beginner's Guide to the Django Rest Framework Getting Started with Django Rest Framework and AngularJS End to end web app with Django-Rest-Framework AngularJS Start Your API - django-rest-framework part 1 Permissions Authentication - django-rest-framework part 2 ViewSets and Routers - django-rest-framework part 3 Django Rest Framework User Endpoint Check credentials using Django Rest Framework Videos Ember and Django Part 1 (Video) Django Rest Framework Part 1 (Video) Pyowa July 2013 - Django Rest Framework (Video) django-rest-framework and angularjs (Video) Articles Web API performance: profiling Django REST framework API Development with Django and Django REST Framework Blog posts about Django REST framework Documentations Classy Django REST Framework",
+ "text": "",
"title": "Other Resources"
},
+ {
+ "location": "/topics/third-party-resources/#tutorials",
+ "text": "Beginner's Guide to the Django Rest Framework Getting Started with Django Rest Framework and AngularJS End to end web app with Django-Rest-Framework AngularJS Start Your API - django-rest-framework part 1 Permissions Authentication - django-rest-framework part 2 ViewSets and Routers - django-rest-framework part 3 Django Rest Framework User Endpoint Check credentials using Django Rest Framework Django REST Framework course",
+ "title": "Tutorials"
+ },
+ {
+ "location": "/topics/third-party-resources/#videos",
+ "text": "Ember and Django Part 1 (Video) Django Rest Framework Part 1 (Video) Pyowa July 2013 - Django Rest Framework (Video) django-rest-framework and angularjs (Video)",
+ "title": "Videos"
+ },
+ {
+ "location": "/topics/third-party-resources/#articles",
+ "text": "Web API performance: profiling Django REST framework API Development with Django and Django REST Framework Blog posts about Django REST framework",
+ "title": "Articles"
+ },
+ {
+ "location": "/topics/third-party-resources/#documentations",
+ "text": "Classy Django REST Framework",
+ "title": "Documentations"
+ },
{
"location": "/topics/contributing/",
"text": "Contributing to REST framework\n\n\n\n\nThe world can only really be changed one piece at a time. The art is picking that piece.\n\n\n \nTim Berners-Lee\n\n\n\n\nThere are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.\n\n\nCommunity\n\n\nThe most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.\n\n\nIf you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.\n\n\nOther really great ways you can help move the community forward include helping to answer questions on the \ndiscussion group\n, or setting up an \nemail alert on StackOverflow\n so that you get notified of any new questions with the \ndjango-rest-framework\n tag.\n\n\nWhen answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.\n\n\nCode of conduct\n\n\nPlease keep the tone polite \n professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.\n\n\nBe mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.\n\n\nThe \nDjango code of conduct\n gives a fuller set of guidelines for participating in community forums.\n\n\nIssues\n\n\nIt's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the \ndiscussion group\n. Feature requests, bug reports and other issues should be raised on the GitHub \nissue tracker\n.\n\n\nSome tips on good issue reporting:\n\n\n\n\nWhen describing issues try to phrase your ticket in terms of the \nbehavior\n you think needs changing rather than the \ncode\n you think need changing.\n\n\nSearch the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.\n\n\nIf reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.\n\n\nFeature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.\n\n\nClosing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.\n\n\n\n\nTriaging issues\n\n\nGetting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to\n\n\n\n\nRead through the ticket - does it make sense, is it missing any context that would help explain it better?\n\n\nIs the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?\n\n\nIf the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?\n\n\nIf the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?\n\n\nIf a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.\n\n\n\n\nDevelopment\n\n\nTo start developing on Django REST framework, clone the repo:\n\n\ngit clone git@github.com:tomchristie/django-rest-framework.git\n\n\n\nChanges should broadly follow the \nPEP 8\n style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.\n\n\nTesting\n\n\nTo run the tests, clone the repository, and then:\n\n\n# Setup the virtual environment\nvirtualenv env\nsource env/bin/activate\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py\n\n\n\nTest options\n\n\nRun using a more concise output style.\n\n\n./runtests.py -q\n\n\n\nRun the tests using a more concise output style, no coverage, no flake8.\n\n\n./runtests.py --fast\n\n\n\nDon't run the flake8 code linting.\n\n\n./runtests.py --nolint\n\n\n\nOnly run the flake8 code linting, don't run the tests.\n\n\n./runtests.py --lintonly\n\n\n\nRun the tests for a given test case.\n\n\n./runtests.py MyTestCase\n\n\n\nRun the tests for a given test method.\n\n\n./runtests.py MyTestCase.test_this_method\n\n\n\nShorter form to run the tests for a given test method.\n\n\n./runtests.py test_this_method\n\n\n\nNote: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.\n\n\nRunning against multiple environments\n\n\nYou can also use the excellent \ntox\n testing tool to run the tests against all supported versions of Python and Django. Install \ntox\n globally, and then simply run:\n\n\ntox\n\n\n\nPull requests\n\n\nIt's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.\n\n\nIt's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.\n\n\nIt's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.\n\n\nGitHub's documentation for working on pull requests is \navailable here\n.\n\n\nAlways run the tests before submitting pull requests, and ideally run \ntox\n in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.\n\n\nOnce you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.\n\n\n\n\nAbove: Travis build notifications\n\n\nManaging compatibility issues\n\n\nSometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the \ncompat.py\n module, and should provide a single common interface that the rest of the codebase can use.\n\n\nDocumentation\n\n\nThe documentation for REST framework is built from the \nMarkdown\n source files in \nthe docs directory\n.\n\n\nThere are many great Markdown editors that make working with the documentation really easy. The \nMou editor for Mac\n is one such editor that comes highly recommended.\n\n\nBuilding the documentation\n\n\nTo build the documentation, install MkDocs with \npip install mkdocs\n and then run the following command.\n\n\nmkdocs build\n\n\n\nThis will build the documentation into the \nsite\n directory.\n\n\nYou can build the documentation and open a preview in a browser window by using the \nserve\n command.\n\n\nmkdocs serve\n\n\n\nLanguage style\n\n\nDocumentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.\n\n\nSome other tips:\n\n\n\n\nKeep paragraphs reasonably short.\n\n\nDon't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.\n\n\n\n\nMarkdown style\n\n\nThere are a couple of conventions you should follow when working on the documentation.\n\n\n1. Headers\n\n\nHeaders should use the hash style. For example:\n\n\n### Some important topic\n\n\n\nThe underline style should not be used. \nDon't do this:\n\n\nSome important topic\n====================\n\n\n\n2. Links\n\n\nLinks should always use the reference style, with the referenced hyperlinks kept at the end of the document.\n\n\nHere is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing\n\n\n\nThis style helps keep the documentation source consistent and readable.\n\n\nIf you are hyperlinking to another REST framework document, you should use a relative link, and link to the \n.md\n suffix. For example:\n\n\n[authentication]: ../api-guide/authentication.md\n\n\n\nLinking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.\n\n\n3. Notes\n\n\nIf you want to draw attention to a note or warning, use a pair of enclosing lines, like so:\n\n\n---\n\n**Note:** A useful documentation note.\n\n---",
@@ -2852,9 +4002,19 @@
},
{
"location": "/topics/contributing/#testing",
- "text": "To run the tests, clone the repository, and then: # Setup the virtual environment\nvirtualenv env\nsource env/bin/activate\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py Test options Run using a more concise output style. ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. ./runtests.py --fast Don't run the flake8 code linting. ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. ./runtests.py --lintonly Run the tests for a given test case. ./runtests.py MyTestCase Run the tests for a given test method. ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. ./runtests.py test_this_method Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. Running against multiple environments You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox globally, and then simply run: tox",
+ "text": "To run the tests, clone the repository, and then: # Setup the virtual environment\nvirtualenv env\nsource env/bin/activate\npip install -r requirements.txt\n\n# Run the tests\n./runtests.py",
"title": "Testing"
},
+ {
+ "location": "/topics/contributing/#test-options",
+ "text": "Run using a more concise output style. ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. ./runtests.py --fast Don't run the flake8 code linting. ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. ./runtests.py --lintonly Run the tests for a given test case. ./runtests.py MyTestCase Run the tests for a given test method. ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. ./runtests.py test_this_method Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.",
+ "title": "Test options"
+ },
+ {
+ "location": "/topics/contributing/#running-against-multiple-environments",
+ "text": "You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox globally, and then simply run: tox",
+ "title": "Running against multiple environments"
+ },
{
"location": "/topics/contributing/#pull-requests",
"text": "It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission. It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests. It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests. GitHub's documentation for working on pull requests is available here . Always run the tests before submitting pull requests, and ideally run tox in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django. Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect. Above: Travis build notifications",
@@ -2882,9 +4042,24 @@
},
{
"location": "/topics/contributing/#markdown-style",
- "text": "There are a couple of conventions you should follow when working on the documentation. 1. Headers Headers should use the hash style. For example: ### Some important topic The underline style should not be used. Don't do this: Some important topic\n==================== 2. Links Links should always use the reference style, with the referenced hyperlinks kept at the end of the document. Here is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing This style helps keep the documentation source consistent and readable. If you are hyperlinking to another REST framework document, you should use a relative link, and link to the .md suffix. For example: [authentication]: ../api-guide/authentication.md Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages. 3. Notes If you want to draw attention to a note or warning, use a pair of enclosing lines, like so: ---\n\n**Note:** A useful documentation note.\n\n---",
+ "text": "There are a couple of conventions you should follow when working on the documentation.",
"title": "Markdown style"
},
+ {
+ "location": "/topics/contributing/#1-headers",
+ "text": "Headers should use the hash style. For example: ### Some important topic The underline style should not be used. Don't do this: Some important topic\n====================",
+ "title": "1. Headers"
+ },
+ {
+ "location": "/topics/contributing/#2-links",
+ "text": "Links should always use the reference style, with the referenced hyperlinks kept at the end of the document. Here is a link to [some other thing][other-thing].\n\nMore text...\n\n[other-thing]: http://example.com/other/thing This style helps keep the documentation source consistent and readable. If you are hyperlinking to another REST framework document, you should use a relative link, and link to the .md suffix. For example: [authentication]: ../api-guide/authentication.md Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.",
+ "title": "2. Links"
+ },
+ {
+ "location": "/topics/contributing/#3-notes",
+ "text": "If you want to draw attention to a note or warning, use a pair of enclosing lines, like so: ---\n\n**Note:** A useful documentation note.\n\n---",
+ "title": "3. Notes"
+ },
{
"location": "/topics/project-management/",
"text": "Project management\n\n\n\n\n\"No one can whistle a symphony; it takes a whole orchestra to play it\"\n\n\n Halford E. Luccock\n\n\n\n\nThis document outlines our project management processes for REST framework.\n\n\nThe aim is to ensure that the project has a high \n\n\"bus factor\"\n, and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.\n\n\n\n\nMaintenance team\n\n\nWe have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.\n\n\nCurrent team\n\n\nThe \nmaintenance team for Q4 2015\n:\n\n\n\n\n@tomchristie\n\n\n@xordoquy\n (Release manager.)\n\n\n@carltongibson\n\n\n@kevin-brown\n\n\n@jpadilla\n\n\n\n\nMaintenance cycles\n\n\nEach maintenance cycle is initiated by an issue being opened with the \nProcess\n label.\n\n\n\n\nTo be considered for a maintainer role simply comment against the issue.\n\n\nExisting members must explicitly opt-in to the next cycle by check-marking their name.\n\n\nThe final decision on the incoming team will be made by \n@tomchristie\n.\n\n\n\n\nMembers of the maintenance team will be added as collaborators to the repository.\n\n\nThe following template should be used for the description of the issue, and serves as the formal process for selecting the team.\n\n\nThis issue is for determining the maintenance team for the *** period.\n\nPlease see the [Project management](http://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.\n\n---\n\n#### Renewing existing members.\n\nThe following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.\n\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n\n---\n\n#### New members.\n\nIf you wish to be considered for this or a future date, please comment against this or subsequent issues.\n\nTo modify this process for future maintenance cycles make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.\n\n\n\nResponsibilities of team members\n\n\nTeam members have the following responsibilities.\n\n\n\n\nClose invalid or resolved tickets.\n\n\nAdd triage labels and milestones to tickets.\n\n\nMerge finalized pull requests.\n\n\nBuild and deploy the documentation, using \nmkdocs gh-deploy\n.\n\n\nBuild and update the included translation packs.\n\n\n\n\nFurther notes for maintainers:\n\n\n\n\nCode changes should come in the form of a pull request - do not push directly to master.\n\n\nMaintainers should typically not merge their own pull requests.\n\n\nEach issue/pull request should have exactly one label once triaged.\n\n\nSearch for un-triaged issues with \nis:open no:label\n.\n\n\n\n\nIt should be noted that participating actively in the REST framework project clearly \ndoes not require being part of the maintenance team\n. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.\n\n\n\n\nRelease process\n\n\nThe release manager is selected on every quarterly maintenance cycle.\n\n\n\n\nThe manager should be selected by \n@tomchristie\n.\n\n\nThe manager will then have the maintainer role added to PyPI package.\n\n\nThe previous manager will then have the maintainer role removed from the PyPI package.\n\n\n\n\nOur PyPI releases will be handled by either the current release manager, or by \n@tomchristie\n. Every release should have an open issue tagged with the \nRelease\n label and marked against the appropriate milestone.\n\n\nThe following template should be used for the description of the issue, and serves as a release checklist.\n\n\nRelease manager is @***.\nPull request is #***.\n\nDuring development cycle:\n\n- [ ] Upload the new content to be translated to [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n\n\nChecklist:\n\n- [ ] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/tomchristie/django-rest-framework/milestones/***).\n- [ ] Update the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).\n- [ ] Confirm with @tomchristie that release is finalized and ready to go.\n- [ ] Ensure that release date is included in pull request.\n- [ ] Merge the release pull request.\n- [ ] Push the package to PyPI with `./setup.py publish`.\n- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.\n- [ ] Deploy the documentation with `mkdocs gh-deploy`.\n- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).\n- [ ] Make a release announcement on twitter.\n- [ ] Close the milestone on GitHub.\n\nTo modify this process for future releases make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.\n\n\n\nWhen pushing the release to PyPI ensure that your environment has been installed from our development \nrequirement.txt\n, so that documentation and PyPI installs are consistently being built against a pinned set of packages.\n\n\n\n\nTranslations\n\n\nThe maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the \ntransifex service\n.\n\n\nManaging Transifex\n\n\nThe \nofficial Transifex client\n is used to upload and download translations to Transifex. The client is installed using pip:\n\n\npip install transifex-client\n\n\n\nTo use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a \n~/.transifexrc\n file which contains your credentials.\n\n\n[https://www.transifex.com]\nusername = ***\ntoken = ***\npassword = ***\nhostname = https://www.transifex.com\n\n\n\nUpload new source files\n\n\nWhen any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run:\n\n\n# 1. Update the source django.po file, which is the US English version.\ncd rest_framework\ndjango-admin.py makemessages -l en_US\n# 2. Push the source django.po file to Transifex.\ncd ..\ntx push -s\n\n\n\nWhen pushing source files, Transifex will update the source strings of a resource to match those from the new source file.\n\n\nHere's how differences between the old and new source files will be handled:\n\n\n\n\nNew strings will be added.\n\n\nModified strings will be added as well.\n\n\nStrings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then \nTransifex Translation Memory\n will automatically include the translation string.\n\n\n\n\nDownload translations\n\n\nWhen a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run:\n\n\n# 3. Pull the translated django.po files from Transifex.\ntx pull -a\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages\n\n\n\n\n\nProject requirements\n\n\nAll our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the \nrequirements\n directory. The requirements files are referenced from the \ntox.ini\n configuration file, ensuring we have a single source of truth for package versions used in testing.\n\n\nPackage upgrades should generally be treated as isolated pull requests. You can check if there are any packages available at a newer version, by using the \npip list --outdated\n.\n\n\n\n\nProject ownership\n\n\nThe PyPI package is owned by \n@tomchristie\n. As a backup \n@j4mie\n also has ownership of the package.\n\n\nIf \n@tomchristie\n ceases to participate in the project then \n@j4mie\n has responsibility for handing over ownership duties.\n\n\nOutstanding management \n ownership issues\n\n\nThe following issues still need to be addressed:\n\n\n\n\nConsider moving the repo into a proper GitHub organization\n.\n\n\nEnsure \n@jamie\n has back-up access to the \ndjango-rest-framework.org\n domain setup and admin.\n\n\nDocument ownership of the \nlive example\n API.\n\n\nDocument ownership of the \nmailing list\n and IRC channel.\n\n\nDocument ownership and management of the security mailing list.",
@@ -2897,9 +4072,24 @@
},
{
"location": "/topics/project-management/#maintenance-team",
- "text": "We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate. Current team The maintenance team for Q4 2015 : @tomchristie @xordoquy (Release manager.) @carltongibson @kevin-brown @jpadilla Maintenance cycles Each maintenance cycle is initiated by an issue being opened with the Process label. To be considered for a maintainer role simply comment against the issue. Existing members must explicitly opt-in to the next cycle by check-marking their name. The final decision on the incoming team will be made by @tomchristie . Members of the maintenance team will be added as collaborators to the repository. The following template should be used for the description of the issue, and serves as the formal process for selecting the team. This issue is for determining the maintenance team for the *** period.\n\nPlease see the [Project management](http://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.\n\n---\n\n#### Renewing existing members.\n\nThe following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.\n\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n\n---\n\n#### New members.\n\nIf you wish to be considered for this or a future date, please comment against this or subsequent issues.\n\nTo modify this process for future maintenance cycles make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation. Responsibilities of team members Team members have the following responsibilities. Close invalid or resolved tickets. Add triage labels and milestones to tickets. Merge finalized pull requests. Build and deploy the documentation, using mkdocs gh-deploy . Build and update the included translation packs. Further notes for maintainers: Code changes should come in the form of a pull request - do not push directly to master. Maintainers should typically not merge their own pull requests. Each issue/pull request should have exactly one label once triaged. Search for un-triaged issues with is:open no:label . It should be noted that participating actively in the REST framework project clearly does not require being part of the maintenance team . Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.",
+ "text": "We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.",
"title": "Maintenance team"
},
+ {
+ "location": "/topics/project-management/#current-team",
+ "text": "The maintenance team for Q4 2015 : @tomchristie @xordoquy (Release manager.) @carltongibson @kevin-brown @jpadilla",
+ "title": "Current team"
+ },
+ {
+ "location": "/topics/project-management/#maintenance-cycles",
+ "text": "Each maintenance cycle is initiated by an issue being opened with the Process label. To be considered for a maintainer role simply comment against the issue. Existing members must explicitly opt-in to the next cycle by check-marking their name. The final decision on the incoming team will be made by @tomchristie . Members of the maintenance team will be added as collaborators to the repository. The following template should be used for the description of the issue, and serves as the formal process for selecting the team. This issue is for determining the maintenance team for the *** period.\n\nPlease see the [Project management](http://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.\n\n---\n\n#### Renewing existing members.\n\nThe following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.\n\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n- [ ] @***\n\n---\n\n#### New members.\n\nIf you wish to be considered for this or a future date, please comment against this or subsequent issues.\n\nTo modify this process for future maintenance cycles make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.",
+ "title": "Maintenance cycles"
+ },
+ {
+ "location": "/topics/project-management/#responsibilities-of-team-members",
+ "text": "Team members have the following responsibilities. Close invalid or resolved tickets. Add triage labels and milestones to tickets. Merge finalized pull requests. Build and deploy the documentation, using mkdocs gh-deploy . Build and update the included translation packs. Further notes for maintainers: Code changes should come in the form of a pull request - do not push directly to master. Maintainers should typically not merge their own pull requests. Each issue/pull request should have exactly one label once triaged. Search for un-triaged issues with is:open no:label . It should be noted that participating actively in the REST framework project clearly does not require being part of the maintenance team . Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.",
+ "title": "Responsibilities of team members"
+ },
{
"location": "/topics/project-management/#release-process",
"text": "The release manager is selected on every quarterly maintenance cycle. The manager should be selected by @tomchristie . The manager will then have the maintainer role added to PyPI package. The previous manager will then have the maintainer role removed from the PyPI package. Our PyPI releases will be handled by either the current release manager, or by @tomchristie . Every release should have an open issue tagged with the Release label and marked against the appropriate milestone. The following template should be used for the description of the issue, and serves as a release checklist. Release manager is @***.\nPull request is #***.\n\nDuring development cycle:\n\n- [ ] Upload the new content to be translated to [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n\n\nChecklist:\n\n- [ ] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/tomchristie/django-rest-framework/milestones/***).\n- [ ] Update the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).\n- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).\n- [ ] Confirm with @tomchristie that release is finalized and ready to go.\n- [ ] Ensure that release date is included in pull request.\n- [ ] Merge the release pull request.\n- [ ] Push the package to PyPI with `./setup.py publish`.\n- [ ] Tag the release, with `git tag -a *.*.* -m 'version *.*.*'; git push --tags`.\n- [ ] Deploy the documentation with `mkdocs gh-deploy`.\n- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).\n- [ ] Make a release announcement on twitter.\n- [ ] Close the milestone on GitHub.\n\nTo modify this process for future releases make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation. When pushing the release to PyPI ensure that your environment has been installed from our development requirement.txt , so that documentation and PyPI installs are consistently being built against a pinned set of packages.",
@@ -2907,9 +4097,24 @@
},
{
"location": "/topics/project-management/#translations",
- "text": "The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the transifex service . Managing Transifex The official Transifex client is used to upload and download translations to Transifex. The client is installed using pip: pip install transifex-client To use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a ~/.transifexrc file which contains your credentials. [https://www.transifex.com]\nusername = ***\ntoken = ***\npassword = ***\nhostname = https://www.transifex.com Upload new source files When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run: # 1. Update the source django.po file, which is the US English version.\ncd rest_framework\ndjango-admin.py makemessages -l en_US\n# 2. Push the source django.po file to Transifex.\ncd ..\ntx push -s When pushing source files, Transifex will update the source strings of a resource to match those from the new source file. Here's how differences between the old and new source files will be handled: New strings will be added. Modified strings will be added as well. Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then Transifex Translation Memory will automatically include the translation string. Download translations When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run: # 3. Pull the translated django.po files from Transifex.\ntx pull -a\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages",
+ "text": "The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the transifex service .",
"title": "Translations"
},
+ {
+ "location": "/topics/project-management/#managing-transifex",
+ "text": "The official Transifex client is used to upload and download translations to Transifex. The client is installed using pip: pip install transifex-client To use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a ~/.transifexrc file which contains your credentials. [https://www.transifex.com]\nusername = ***\ntoken = ***\npassword = ***\nhostname = https://www.transifex.com",
+ "title": "Managing Transifex"
+ },
+ {
+ "location": "/topics/project-management/#upload-new-source-files",
+ "text": "When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run: # 1. Update the source django.po file, which is the US English version.\ncd rest_framework\ndjango-admin.py makemessages -l en_US\n# 2. Push the source django.po file to Transifex.\ncd ..\ntx push -s When pushing source files, Transifex will update the source strings of a resource to match those from the new source file. Here's how differences between the old and new source files will be handled: New strings will be added. Modified strings will be added as well. Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then Transifex Translation Memory will automatically include the translation string.",
+ "title": "Upload new source files"
+ },
+ {
+ "location": "/topics/project-management/#download-translations",
+ "text": "When a translator has finished translating their work needs to be downloaded from Transifex into the REST framework repository. To do this, run: # 3. Pull the translated django.po files from Transifex.\ntx pull -a\ncd rest_framework\n# 4. Compile the binary .mo files for all supported languages.\ndjango-admin.py compilemessages",
+ "title": "Download translations"
+ },
{
"location": "/topics/project-management/#project-requirements",
"text": "All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the requirements directory. The requirements files are referenced from the tox.ini configuration file, ensuring we have a single source of truth for package versions used in testing. Package upgrades should generally be treated as isolated pull requests. You can check if there are any packages available at a newer version, by using the pip list --outdated .",
@@ -2917,12 +4122,17 @@
},
{
"location": "/topics/project-management/#project-ownership",
- "text": "The PyPI package is owned by @tomchristie . As a backup @j4mie also has ownership of the package. If @tomchristie ceases to participate in the project then @j4mie has responsibility for handing over ownership duties. Outstanding management ownership issues The following issues still need to be addressed: Consider moving the repo into a proper GitHub organization . Ensure @jamie has back-up access to the django-rest-framework.org domain setup and admin. Document ownership of the live example API. Document ownership of the mailing list and IRC channel. Document ownership and management of the security mailing list.",
+ "text": "The PyPI package is owned by @tomchristie . As a backup @j4mie also has ownership of the package. If @tomchristie ceases to participate in the project then @j4mie has responsibility for handing over ownership duties.",
"title": "Project ownership"
},
+ {
+ "location": "/topics/project-management/#outstanding-management-ownership-issues",
+ "text": "The following issues still need to be addressed: Consider moving the repo into a proper GitHub organization . Ensure @jamie has back-up access to the django-rest-framework.org domain setup and admin. Document ownership of the live example API. Document ownership of the mailing list and IRC channel. Document ownership and management of the security mailing list.",
+ "title": "Outstanding management & ownership issues"
+ },
{
"location": "/topics/3.0-announcement/",
- "text": "Django REST framework 3.0\n\n\nThe 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.\n\n\nThis release is incremental in nature. There \nare\n some breaking API changes, and upgrading \nwill\n require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.\n\n\nThe difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.\n\n\n3.0 is the first of three releases that have been funded by our recent \nKickstarter campaign\n.\n\n\nAs ever, a huge thank you to our many \nwonderful sponsors\n. 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.\n\n\n\n\nNew features\n\n\nNotable features of this new release include:\n\n\n\n\nPrintable representations on serializers that allow you to inspect exactly what fields are present on the instance.\n\n\nSimple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit \nModelSerializer\n class and the explicit \nSerializer\n class.\n\n\nA new \nBaseSerializer\n class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.\n\n\nA cleaner fields API including new classes such as \nListField\n and \nMultipleChoiceField\n.\n\n\nSuper simple default implementations\n for the generic views.\n\n\nSupport for overriding how validation errors are handled by your API.\n\n\nA metadata API that allows you to customize how \nOPTIONS\n requests are handled by your API.\n\n\nA more compact JSON output with unicode style encoding turned on by default.\n\n\nTemplated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.\n\n\n\n\nSignificant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two \nKickstarter stretch goals\n - \"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.\n\n\n\n\nREST framework: Under the hood.\n\n\nThis talk from the \nDjango: Under the Hood\n event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.\n\n\n\n\n\n\n\nBelow is an in-depth guide to the API changes and migration notes for 3.0.\n\n\nRequest objects\n\n\nThe \n.data\n and \n.query_params\n properties.\n\n\nThe usage of \nrequest.DATA\n and \nrequest.FILES\n is now pending deprecation in favor of a single \nrequest.data\n attribute that contains \nall\n the parsed data.\n\n\nHaving 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.\n\n\nYou may now pass all the request data to a serializer class in a single argument:\n\n\n# Do this...\nExampleSerializer(data=request.data)\n\n\n\nInstead of passing the files argument separately:\n\n\n# Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES)\n\n\n\nThe usage of \nrequest.QUERY_PARAMS\n is now pending deprecation in favor of the lowercased \nrequest.query_params\n.\n\n\n\n\nSerializers\n\n\nSingle-step object creation.\n\n\nPreviously the serializers used a two-step object creation, as follows:\n\n\n\n\nValidating the data would create an object instance. This instance would be available as \nserializer.object\n.\n\n\nCalling \nserializer.save()\n would then save the object instance to the database.\n\n\n\n\nThis style is in-line with how the \nModelForm\n class works in Django, but is problematic for a number of reasons:\n\n\n\n\nSome 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 \n.save()\n is called.\n\n\nInstantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. \nExampleModel.objects.create(...)\n. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.\n\n\nThe 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?\n\n\n\n\nWe now use single-step object creation, like so:\n\n\n\n\nValidating the data makes the cleaned data available as \nserializer.validated_data\n.\n\n\nCalling \nserializer.save()\n then saves and returns the new object instance.\n\n\n\n\nThe resulting API changes are further detailed below.\n\n\nThe \n.create()\n and \n.update()\n methods.\n\n\nThe \n.restore_object()\n method is now removed, and we instead have two separate methods, \n.create()\n and \n.update()\n. These methods work slightly different to the previous \n.restore_object()\n.\n\n\nWhen using the \n.create()\n and \n.update()\n methods you should both create \nand save\n the object instance. This is in contrast to the previous \n.restore_object()\n behavior that would instantiate the object but not save it.\n\n\nThese methods also replace the optional \n.save_object()\n method, which no longer exists.\n\n\nThe following example from the tutorial previously used \nrestore_object()\n to handle both creating and updating object instances.\n\n\ndef restore_object(self, attrs, instance=None):\n if instance:\n # Update existing instance\n instance.title = attrs.get('title', instance.title)\n instance.code = attrs.get('code', instance.code)\n instance.linenos = attrs.get('linenos', instance.linenos)\n instance.language = attrs.get('language', instance.language)\n instance.style = attrs.get('style', instance.style)\n return instance\n\n # Create new instance\n return Snippet(**attrs)\n\n\n\nThis would now be split out into two separate methods.\n\n\ndef update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\ndef create(self, validated_data):\n return Snippet.objects.create(**validated_data)\n\n\n\nNote that these methods should return the newly created object instance.\n\n\nUse \n.validated_data\n instead of \n.object\n.\n\n\nYou must now use the \n.validated_data\n attribute if you need to inspect the data before saving, rather than using the \n.object\n attribute, which no longer exists.\n\n\nFor example the following code \nis no longer valid\n:\n\n\nif serializer.is_valid():\n name = serializer.object.name # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.object.user = request.user # Include the user when saving.\n serializer.save()\n\n\n\nInstead of using \n.object\n to inspect a partially constructed instance, you would now use \n.validated_data\n to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the \n.save()\n method as keyword arguments.\n\n\nThe corresponding code would now look like this:\n\n\nif serializer.is_valid():\n name = serializer.validated_data['name'] # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.save(user=request.user) # Include the user when saving.\n\n\n\nUsing \n.is_valid(raise_exception=True)\n\n\nThe \n.is_valid()\n method now takes an optional boolean flag, \nraise_exception\n.\n\n\nCalling \n.is_valid(raise_exception=True)\n will cause a \nValidationError\n 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.\n\n\nThe handling and formatting of error responses may be altered globally by using the \nEXCEPTION_HANDLER\n settings key.\n\n\nThis 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.\n\n\nUsing \nserializers.ValidationError\n.\n\n\nPreviously \nserializers.ValidationError\n error was simply a synonym for \ndjango.core.exceptions.ValidationError\n. This has now been altered so that it inherits from the standard \nAPIException\n base class.\n\n\nThe reason behind this is that Django's \nValidationError\n 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.\n\n\nFor 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 \nserializers.ValidationError\n exception class, and not Django's built-in exception.\n\n\nWe strongly recommend that you use the namespaced import style of \nimport serializers\n and not \nfrom serializers import ValidationError\n in order to avoid any potential confusion.\n\n\nChange to \nvalidate_\nfield_name\n.\n\n\nThe \nvalidate_\nfield_name\n 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:\n\n\ndef validate_score(self, attrs, source):\n if attrs['score'] % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return attrs\n\n\n\nThis is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.\n\n\ndef validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value\n\n\n\nAny ad-hoc validation that applies to more than one field should go in the \n.validate(self, attrs)\n method as usual.\n\n\nBecause \n.validate_\nfield_name\n 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 \n.validate()\n instead.\n\n\nYou can either return \nnon_field_errors\n from the validate method by raising a simple \nValidationError\n\n\ndef validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error')\n\n\n\nAlternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the \nValidationError\n, like so:\n\n\ndef validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'})\n\n\n\nThis ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.\n\n\nRemoval of \ntransform_\nfield_name\n.\n\n\nThe under-used \ntransform_\nfield_name\n on serializer classes is no longer provided. Instead you should just override \nto_representation()\n if you need to apply any modifications to the representation style.\n\n\nFor example:\n\n\ndef to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n\n\n\nDropping 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.\n\n\nIf you absolutely need to preserve \ntransform_\nfield_name\n 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:\n\n\nclass BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_\nfield_name\n` behavior.\n \"\"\"\n def to_representation(self, instance):\n ret = super(BaseModelSerializer, self).to_representation(instance)\n for key, value in ret.items():\n method = getattr(self, 'transform_' + key, None)\n if method is not None:\n ret[key] = method(value)\n return ret\n\n\n\nDifferences between ModelSerializer validation and ModelForm.\n\n\nThis change also means that we no longer use the \n.full_clean()\n 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 \nModelSerializer\n classes that can't also be easily replicated on regular \nSerializer\n classes.\n\n\nFor 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.\n\n\nThe one difference that you do need to note is that the \n.clean()\n method will not be called as part of serializer validation, as it would be if using a \nModelForm\n. Use the serializer \n.validate()\n method to perform a final validation step on incoming data where required.\n\n\nThere may be some cases where you really do need to keep validation logic in the model \n.clean()\n method, and cannot instead separate it into the serializer \n.validate()\n. You can do so by explicitly instantiating a model instance in the \n.validate()\n method.\n\n\ndef validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs\n\n\n\nAgain, 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.\n\n\nWritable nested serialization.\n\n\nREST 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:\n\n\n\n\nThere can be complex dependencies involved in order of saving multiple related model instances.\n\n\nIt's unclear what behavior the user should expect when related models are passed \nNone\n data.\n\n\nIt's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.\n\n\n\n\nUsing the \ndepth\n option on \nModelSerializer\n will now create \nread-only nested serializers\n by default.\n\n\nIf you try to use a writable nested serializer without writing a custom \ncreate()\n and/or \nupdate()\n method you'll see an assertion error when you attempt to save the serializer. For example:\n\n\n class ProfileSerializer(serializers.ModelSerializer):\n\n class Meta:\n\n model = Profile\n\n fields = ('address', 'phone')\n\n\n\n class UserSerializer(serializers.ModelSerializer):\n\n profile = ProfileSerializer()\n\n class Meta:\n\n model = User\n\n fields = ('username', 'email', 'profile')\n\n\n\n data = {\n\n 'username': 'lizzy',\n\n 'email': 'lizzy@example.com',\n\n 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n\n }\n\n\n\n serializer = UserSerializer(data=data)\n\n serializer.save()\nAssertionError: 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.\n\n\n\nTo use writable nested serialization you'll want to declare a nested field on the serializer class, and write the \ncreate()\n and/or \nupdate()\n methods explicitly.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n\n\n\nThe single-step object creation makes this far simpler and more obvious than the previous \n.restore_object()\n behavior.\n\n\nPrintable serializer representations.\n\n\nSerializer instances now support a printable representation that allows you to inspect the fields present on the instance.\n\n\nFor instance, given the following example model:\n\n\nclass LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User)\n\n\n\nLet's create a simple \nModelSerializer\n class corresponding to the \nLocationRating\n model.\n\n\nclass LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating\n\n\n\nWe can now inspect the serializer representation in the Django shell, using \npython manage.py shell\n...\n\n\n serializer = LocationRatingSerializer()\n\n print(serializer) # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n id = IntegerField(label='ID', read_only=True)\n location = CharField(max_length=100)\n rating = IntegerField()\n created_by = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nThe \nextra_kwargs\n option.\n\n\nThe \nwrite_only_fields\n option on \nModelSerializer\n has been moved to \nPendingDeprecation\n and replaced with a more generic \nextra_kwargs\n.\n\n\nclass MySerializer(serializer.ModelSerializer):\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'is_admin': {'write_only': True}\n }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.ModelSerializer):\n is_admin = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n\n\n\nThe \nread_only_fields\n option remains as a convenient shortcut for the more common case.\n\n\nChanges to \nHyperlinkedModelSerializer\n.\n\n\nThe \nview_name\n and \nlookup_field\n options have been moved to \nPendingDeprecation\n. They are no longer required, as you can use the \nextra_kwargs\n argument instead:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'url': {'lookup_field': 'uuid'}\n }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='mymodel-detail',\n lookup_field='uuid'\n )\n\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n\n\n\nFields for model methods and properties.\n\n\nWith \nModelSerializer\n you can now specify field names in the \nfields\n option that refer to model methods or properties. For example, suppose you have the following model:\n\n\nclass Invitation(models.Model):\n created = models.DateTimeField()\n to_email = models.EmailField()\n message = models.CharField(max_length=1000)\n\n def expiry_date(self):\n return self.created + datetime.timedelta(days=30)\n\n\n\nYou can include \nexpiry_date\n as a field option on a \nModelSerializer\n class.\n\n\nclass InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ('to_email', 'message', 'expiry_date')\n\n\n\nThese fields will be mapped to \nserializers.ReadOnlyField()\n instances.\n\n\n serializer = InvitationSerializer()\n\n print repr(serializer)\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()\n\n\n\nThe \nListSerializer\n class.\n\n\nThe \nListSerializer\n class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.\n\n\nclass MultipleUserSerializer(ListSerializer):\n child = UserSerializer()\n\n\n\nYou can also still use the \nmany=True\n argument to serializer classes. It's worth noting that \nmany=True\n argument transparently creates a \nListSerializer\n instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.\n\n\nYou will typically want to \ncontinue to use the existing \nmany=True\n flag\n rather than declaring \nListSerializer\n classes explicitly, but declaring the classes explicitly can be useful if you need to write custom \ncreate\n or \nupdate\n methods for bulk updates, or provide for other custom behavior.\n\n\nSee also the new \nListField\n class, which validates input in the same way, but does not include the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nBaseSerializer\n class.\n\n\nREST framework now includes a simple \nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns an errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes.\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes.\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) \n 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n\n\n\nCreating new generic serializers with \nBaseSerializer\n.\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n\n\n\n\n\nSerializer fields\n\n\nThe \nField\n and \nReadOnly\n field classes.\n\n\nThere are some minor tweaks to the field base classes.\n\n\nPreviously we had these two base classes:\n\n\n\n\nField\n as the base class for read-only fields. A default implementation was included for serializing data.\n\n\nWritableField\n as the base class for read-write fields.\n\n\n\n\nWe now use the following:\n\n\n\n\nField\n is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.\n\n\nReadOnlyField\n is a concrete implementation for read-only fields that simply returns the attribute value without modification.\n\n\n\n\nThe \nrequired\n, \nallow_null\n, \nallow_blank\n and \ndefault\n arguments.\n\n\nREST framework now has more explicit and clear control over validating empty values for fields.\n\n\nPreviously the meaning of the \nrequired=False\n 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 \nNone\n or the empty string.\n\n\nWe now have a better separation, with separate \nrequired\n, \nallow_null\n and \nallow_blank\n arguments.\n\n\nThe following set of arguments are used to control validation of empty values:\n\n\n\n\nrequired=False\n: The value does not need to be present in the input, and will not be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\ndefault=\nvalue\n: The value does not need to be present in the input, and a default value will be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\nallow_null=True\n: \nNone\n is a valid input.\n\n\nallow_blank=True\n: \n''\n is valid input. For \nCharField\n and subclasses only.\n\n\n\n\nTypically you'll want to use \nrequired=False\n if the corresponding model field has a default value, and additionally set either \nallow_null=True\n or \nallow_blank=True\n if required.\n\n\nThe \ndefault\n argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the \nrequired\n argument when a default is specified, and doing so will result in an error.\n\n\nCoercing output types.\n\n\nThe previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an \nIntegerField\n 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.\n\n\nRemoval of \n.validate()\n.\n\n\nThe \n.validate()\n method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override \nto_internal_value()\n.\n\n\nclass UppercaseCharField(serializers.CharField):\n def to_internal_value(self, data):\n value = super(UppercaseCharField, self).to_internal_value(data)\n if value != value.upper():\n raise serializers.ValidationError('The input should be uppercase only.')\n return value\n\n\n\nPreviously validation errors could be raised in either \n.to_native()\n or \n.validate()\n, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.\n\n\nThe \nListField\n class.\n\n\nThe \nListField\n class has now been added. This field validates list input. It takes a \nchild\n keyword argument which is used to specify the field used to validate each item in the list. For example:\n\n\nscores = ListField(child=IntegerField(min_value=0, max_value=100))\n\n\n\nYou can also use a declarative style to create new subclasses of \nListField\n, like this:\n\n\nclass ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100)\n\n\n\nWe can now use the \nScoresField\n class inside another serializer:\n\n\nscores = ScoresField()\n\n\n\nSee also the new \nListSerializer\n class, which validates input in the same way, but also includes the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nChoiceField\n class may now accept a flat list.\n\n\nThe \nChoiceField\n class may now accept a list of choices in addition to the existing style of using a list of pairs of \n(name, display_value)\n. The following is now valid:\n\n\ncolor = ChoiceField(choices=['red', 'green', 'blue'])\n\n\n\nThe \nMultipleChoiceField\n class.\n\n\nThe \nMultipleChoiceField\n class has been added. This field acts like \nChoiceField\n, but returns a set, which may include none, one or many of the valid choices.\n\n\nChanges to the custom field API.\n\n\nThe \nfrom_native(self, value)\n and \nto_native(self, data)\n method names have been replaced with the more obviously named \nto_internal_value(self, data)\n and \nto_representation(self, value)\n.\n\n\nThe \nfield_from_native()\n and \nfield_to_native()\n 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...\n\n\ndef field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__\n\n\n\nNow if you need to access the entire object you'll instead need to override one or both of the following:\n\n\n\n\nUse \nget_attribute\n to modify the attribute value passed to \nto_representation()\n.\n\n\nUse \nget_value\n to modify the data value passed \nto_internal_value()\n.\n\n\n\n\nFor example:\n\n\ndef get_attribute(self, obj):\n # Pass the entire object through to `to_representation()`,\n # instead of the standard attribute lookup.\n return obj\n\ndef to_representation(self, value):\n return value.__class__.__name__\n\n\n\nExplicit \nqueryset\n required on relational fields.\n\n\nPreviously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a \nModelSerializer\n.\n\n\nThis code \nwould be valid\n in \n2.4.3\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account\n\n\n\nHowever this code \nwould not be valid\n in \n3.0\n:\n\n\n# Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ...\n\n\n\nThe queryset argument is now always required for writable relational fields.\nThis removes some magic and makes it easier and more obvious to move between implicit \nModelSerializer\n classes and explicit \nSerializer\n classes.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account\n\n\n\nThe \nqueryset\n argument is only ever required for writable fields, and is not required or valid for fields with \nread_only=True\n.\n\n\nOptional argument to \nSerializerMethodField\n.\n\n\nThe argument to \nSerializerMethodField\n is now optional, and defaults to \nget_\nfield_name\n. For example the following is valid:\n\n\nclass AccountSerializer(serializers.Serializer):\n # `method_name='get_billing_details'` by default.\n billing_details = serializers.SerializerMethodField()\n\n def get_billing_details(self, account):\n return calculate_billing(account)\n\n\n\nIn 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 \nwill raise an error\n:\n\n\nbilling_details = serializers.SerializerMethodField('get_billing_details')\n\n\n\nEnforcing consistent \nsource\n usage.\n\n\nI've see several codebases that unnecessarily include the \nsource\n argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that \nsource\n is usually not required.\n\n\nThe following usage will \nnow raise an error\n:\n\n\nemail = serializers.EmailField(source='email')\n\n\n\nThe \nUniqueValidator\n and \nUniqueTogetherValidator\n classes.\n\n\nREST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit \nSerializer\n class instead of using \nModelSerializer\n.\n\n\nThe \nUniqueValidator\n should be applied to a serializer field, and takes a single \nqueryset\n argument.\n\n\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n created = serializers.DateTimeField(read_only=True)\n name = serializers.CharField(\n max_length=100,\n validators=UniqueValidator(queryset=Organization.objects.all())\n )\n\n\n\nThe \nUniqueTogetherValidator\n should be applied to a serializer, and takes a \nqueryset\n argument and a \nfields\n argument which should be a list or tuple of field names.\n\n\nclass RaceResultSerializer(serializers.Serializer):\n category = serializers.ChoiceField(['5k', '10k'])\n position = serializers.IntegerField()\n name = serializers.CharField(max_length=100)\n\n class Meta:\n validators = [UniqueTogetherValidator(\n queryset=RaceResult.objects.all(),\n fields=('category', 'position')\n )]\n\n\n\nThe \nUniqueForDateValidator\n classes.\n\n\nREST framework also now includes explicit validator classes for validating the \nunique_for_date\n, \nunique_for_month\n, and \nunique_for_year\n model field constraints. These are used internally instead of calling into \nModel.full_clean()\n.\n\n\nThese classes are documented in the \nValidators\n section of the documentation.\n\n\n\n\nGeneric views\n\n\nSimplification of view logic.\n\n\nThe view logic for the default method handlers has been significantly simplified, due to the new serializers API.\n\n\nChanges to pre/post save hooks.\n\n\nThe \npre_save\n and \npost_save\n hooks no longer exist, but are replaced with \nperform_create(self, serializer)\n and \nperform_update(self, serializer)\n.\n\n\nThese methods should save the object instance by calling \nserializer.save()\n, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.\n\n\nFor example:\n\n\ndef perform_create(self, serializer):\n # Include the owner attribute directly, rather than from request data.\n instance = serializer.save(owner=self.request.user)\n # Perform a custom post-save action.\n send_email(instance.to_email, instance.message)\n\n\n\nThe \npre_delete\n and \npost_delete\n hooks no longer exist, and are replaced with \n.perform_destroy(self, instance)\n, which should delete the instance and perform any custom actions.\n\n\ndef perform_destroy(self, instance):\n # Perform a custom pre-delete action.\n send_deletion_alert(user=instance.created_by, deleted=instance)\n # Delete the object instance.\n instance.delete()\n\n\n\nRemoval of view attributes.\n\n\nThe \n.object\n and \n.object_list\n 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.\n\n\nI would personally recommend that developers treat view instances as immutable objects in their application code.\n\n\nPUT as create.\n\n\nAllowing \nPUT\n 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 \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n 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.\n\n\nIf you need to restore the previous behavior you may want to include \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\nCustomizing error responses.\n\n\nThe generic views now raise \nValidationFailed\n exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a \n400 Bad Request\n response directly.\n\n\nThis 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.\n\n\n\n\nThe metadata API\n\n\nBehavior for dealing with \nOPTIONS\n 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.\n\n\nThis makes it far easier to use a different style for \nOPTIONS\n responses throughout your API, and makes it possible to create third-party metadata policies.\n\n\n\n\nSerializers as HTML forms\n\n\nREST framework 3.0 includes templated HTML form rendering for serializers.\n\n\nThis API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.\n\n\nSignificant changes that you do need to be aware of include:\n\n\n\n\nNested HTML forms are now supported, for example, a \nUserSerializer\n with a nested \nProfileSerializer\n will now render a nested \nfieldset\n when used in the browsable API.\n\n\nNested lists of HTML forms are not yet supported, but are planned for 3.1.\n\n\nBecause we now use templated HTML form generation, \nthe \nwidget\n option is no longer available for serializer fields\n. You can instead control the template that is used for a given field, by using the \nstyle\n dictionary.\n\n\n\n\nThe \nstyle\n keyword argument for serializer fields.\n\n\nThe \nstyle\n keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the \nHTMLFormRenderer\n uses the \nbase_template\n key to determine which template to render the field with.\n\n\nFor example, to use a \ntextarea\n control instead of the default \ninput\n control, you would use the following\u2026\n\n\nadditional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n)\n\n\n\nSimilarly, to use a radio button control instead of the default \nselect\n control, you would use the following\u2026\n\n\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n)\n\n\n\nThis API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.\n\n\n\n\nAPI style\n\n\nThere are some improvements in the default style we use in our API responses.\n\n\nUnicode JSON by default.\n\n\nUnicode JSON is now the default. The \nUnicodeJSONRenderer\n class no longer exists, and the \nUNICODE_JSON\n setting has been added. To revert this behavior use the new setting:\n\n\nREST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}\n\n\n\nCompact JSON by default.\n\n\nWe now output compact JSON in responses by default. For example, we return:\n\n\n{\"email\":\"amy@example.com\",\"is_admin\":true}\n\n\n\nInstead of the following:\n\n\n{\"email\": \"amy@example.com\", \"is_admin\": true}\n\n\n\nThe \nCOMPACT_JSON\n setting has been added, and can be used to revert this behavior if needed:\n\n\nREST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}\n\n\n\nFile fields as URLs\n\n\nThe \nFileField\n and \nImageField\n classes are now represented as URLs by default. You should ensure you set Django's \nstandard \nMEDIA_URL\n setting\n appropriately, and ensure your application \nserves the uploaded files\n.\n\n\nYou can revert this behavior, and display filenames in the representation by using the \nUPLOADED_FILES_USE_URL\n settings key:\n\n\nREST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n}\n\n\n\nYou can also modify serializer fields individually, using the \nuse_url\n argument:\n\n\nuploaded_file = serializers.FileField(use_url=False)\n\n\n\nAlso note that you should pass the \nrequest\n 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 \nhttps://example.com/url_path/filename.txt\n. For example:\n\n\ncontext = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data)\n\n\n\nIf the request is omitted from the context, the returned URLs will be of the form \n/url_path/filename.txt\n.\n\n\nThrottle headers using \nRetry-After\n.\n\n\nThe custom \nX-Throttle-Wait-Second\n header has now been dropped in favor of the standard \nRetry-After\n header. You can revert this behavior if needed by writing a custom exception handler for your application.\n\n\nDate and time objects as ISO-8859-1 strings in serializer data.\n\n\nDate and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as \nDate\n, \nTime\n and \nDateTime\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by settings the existing \nDATE_FORMAT\n, \nDATETIME_FORMAT\n and \nTIME_FORMAT\n settings keys. Setting these values to \nNone\n instead of their default value of \n'iso-8859-1'\n will result in native objects being returned in serializer data.\n\n\nREST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n}\n\n\n\nYou can also modify serializer fields individually, using the \ndate_format\n, \ntime_format\n and \ndatetime_format\n arguments:\n\n\n# Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)\n\n\n\nDecimals as strings in serializer data.\n\n\nDecimals are now coerced to strings by default in the serializer output. Previously they were returned as \nDecimal\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by using the \nCOERCE_DECIMAL_TO_STRING\n settings key.\n\n\nREST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n}\n\n\n\nOr modify it on an individual serializer field, using the \ncoerce_to_string\n keyword argument.\n\n\n# Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n max_digits=10,\n decimal_places=2,\n coerce_to_string=False\n)\n\n\n\nThe default JSON renderer will return float objects for un-coerced \nDecimal\n instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.\n\n\n\n\nMiscellaneous notes\n\n\n\n\nThe serializer \nChoiceField\n does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.\n\n\nDue 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.\n\n\nSome of the default validation error messages were rewritten and might no longer be pre-translated. You can still \ncreate language files with Django\n if you wish to localize them.\n\n\nAPIException\n subclasses could previously take any arbitrary type in the \ndetail\n argument. These exceptions now use translatable text strings, and as a result call \nforce_text\n on the \ndetail\n argument, which \nmust be a string\n. If you need complex arguments to an \nAPIException\n class, you should subclass it and override the \n__init__()\n method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.\n\n\n\n\n\n\nWhat's coming next\n\n\n3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.\n\n\nThe 3.1 release is planned to address improvements in the following components:\n\n\n\n\nPublic API for using serializers as HTML forms.\n\n\nRequest parsing, mediatypes \n the implementation of the browsable API.\n\n\nIntroduction of a new pagination API.\n\n\nBetter support for API versioning.\n\n\n\n\nThe 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.\n\n\nYou can follow development on the GitHub site, where we use \nmilestones to indicate planning timescales\n.",
+ "text": "Django REST framework 3.0\n\n\nThe 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.\n\n\nThis release is incremental in nature. There \nare\n some breaking API changes, and upgrading \nwill\n require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.\n\n\nThe difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.\n\n\n3.0 is the first of three releases that have been funded by our recent \nKickstarter campaign\n.\n\n\nAs ever, a huge thank you to our many \nwonderful sponsors\n. 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.\n\n\n\n\nNew features\n\n\nNotable features of this new release include:\n\n\n\n\nPrintable representations on serializers that allow you to inspect exactly what fields are present on the instance.\n\n\nSimple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit \nModelSerializer\n class and the explicit \nSerializer\n class.\n\n\nA new \nBaseSerializer\n class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.\n\n\nA cleaner fields API including new classes such as \nListField\n and \nMultipleChoiceField\n.\n\n\nSuper simple default implementations\n for the generic views.\n\n\nSupport for overriding how validation errors are handled by your API.\n\n\nA metadata API that allows you to customize how \nOPTIONS\n requests are handled by your API.\n\n\nA more compact JSON output with unicode style encoding turned on by default.\n\n\nTemplated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.\n\n\n\n\nSignificant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two \nKickstarter stretch goals\n - \"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.\n\n\n\n\nREST framework: Under the hood.\n\n\nThis talk from the \nDjango: Under the Hood\n event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.\n\n\n\n\n\n\n\nBelow is an in-depth guide to the API changes and migration notes for 3.0.\n\n\nRequest objects\n\n\n.query_params\n properties.\nThe \n.data\n and \n\n\nThe usage of \nrequest.DATA\n and \nrequest.FILES\n is now pending deprecation in favor of a single \nrequest.data\n attribute that contains \nall\n the parsed data.\n\n\nHaving 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.\n\n\nYou may now pass all the request data to a serializer class in a single argument:\n\n\n# Do this...\nExampleSerializer(data=request.data)\n\n\n\nInstead of passing the files argument separately:\n\n\n# Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES)\n\n\n\nThe usage of \nrequest.QUERY_PARAMS\n is now pending deprecation in favor of the lowercased \nrequest.query_params\n.\n\n\n\n\nSerializers\n\n\nSingle-step object creation.\n\n\nPreviously the serializers used a two-step object creation, as follows:\n\n\n\n\nValidating the data would create an object instance. This instance would be available as \nserializer.object\n.\n\n\nCalling \nserializer.save()\n would then save the object instance to the database.\n\n\n\n\nThis style is in-line with how the \nModelForm\n class works in Django, but is problematic for a number of reasons:\n\n\n\n\nSome 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 \n.save()\n is called.\n\n\nInstantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. \nExampleModel.objects.create(...)\n. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.\n\n\nThe 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?\n\n\n\n\nWe now use single-step object creation, like so:\n\n\n\n\nValidating the data makes the cleaned data available as \nserializer.validated_data\n.\n\n\nCalling \nserializer.save()\n then saves and returns the new object instance.\n\n\n\n\nThe resulting API changes are further detailed below.\n\n\n.update()\n methods.\nThe \n.create()\n and \n\n\nThe \n.restore_object()\n method is now removed, and we instead have two separate methods, \n.create()\n and \n.update()\n. These methods work slightly different to the previous \n.restore_object()\n.\n\n\nWhen using the \n.create()\n and \n.update()\n methods you should both create \nand save\n the object instance. This is in contrast to the previous \n.restore_object()\n behavior that would instantiate the object but not save it.\n\n\nThese methods also replace the optional \n.save_object()\n method, which no longer exists.\n\n\nThe following example from the tutorial previously used \nrestore_object()\n to handle both creating and updating object instances.\n\n\ndef restore_object(self, attrs, instance=None):\n if instance:\n # Update existing instance\n instance.title = attrs.get('title', instance.title)\n instance.code = attrs.get('code', instance.code)\n instance.linenos = attrs.get('linenos', instance.linenos)\n instance.language = attrs.get('language', instance.language)\n instance.style = attrs.get('style', instance.style)\n return instance\n\n # Create new instance\n return Snippet(**attrs)\n\n\n\nThis would now be split out into two separate methods.\n\n\ndef update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\ndef create(self, validated_data):\n return Snippet.objects.create(**validated_data)\n\n\n\nNote that these methods should return the newly created object instance.\n\n\n.object\n.\nUse \n.validated_data\n instead of \n\n\nYou must now use the \n.validated_data\n attribute if you need to inspect the data before saving, rather than using the \n.object\n attribute, which no longer exists.\n\n\nFor example the following code \nis no longer valid\n:\n\n\nif serializer.is_valid():\n name = serializer.object.name # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.object.user = request.user # Include the user when saving.\n serializer.save()\n\n\n\nInstead of using \n.object\n to inspect a partially constructed instance, you would now use \n.validated_data\n to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the \n.save()\n method as keyword arguments.\n\n\nThe corresponding code would now look like this:\n\n\nif serializer.is_valid():\n name = serializer.validated_data['name'] # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.save(user=request.user) # Include the user when saving.\n\n\n\nUsing \n.is_valid(raise_exception=True)\n\n\nThe \n.is_valid()\n method now takes an optional boolean flag, \nraise_exception\n.\n\n\nCalling \n.is_valid(raise_exception=True)\n will cause a \nValidationError\n 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.\n\n\nThe handling and formatting of error responses may be altered globally by using the \nEXCEPTION_HANDLER\n settings key.\n\n\nThis 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.\n\n\nUsing \nserializers.ValidationError\n.\n\n\nPreviously \nserializers.ValidationError\n error was simply a synonym for \ndjango.core.exceptions.ValidationError\n. This has now been altered so that it inherits from the standard \nAPIException\n base class.\n\n\nThe reason behind this is that Django's \nValidationError\n 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.\n\n\nFor 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 \nserializers.ValidationError\n exception class, and not Django's built-in exception.\n\n\nWe strongly recommend that you use the namespaced import style of \nimport serializers\n and not \nfrom serializers import ValidationError\n in order to avoid any potential confusion.\n\n\nChange to \nvalidate_\nfield_name\n.\n\n\nThe \nvalidate_\nfield_name\n 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:\n\n\ndef validate_score(self, attrs, source):\n if attrs['score'] % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return attrs\n\n\n\nThis is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.\n\n\ndef validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value\n\n\n\nAny ad-hoc validation that applies to more than one field should go in the \n.validate(self, attrs)\n method as usual.\n\n\nBecause \n.validate_\nfield_name\n 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 \n.validate()\n instead.\n\n\nYou can either return \nnon_field_errors\n from the validate method by raising a simple \nValidationError\n\n\ndef validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error')\n\n\n\nAlternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the \nValidationError\n, like so:\n\n\ndef validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'})\n\n\n\nThis ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.\n\n\nRemoval of \ntransform_\nfield_name\n.\n\n\nThe under-used \ntransform_\nfield_name\n on serializer classes is no longer provided. Instead you should just override \nto_representation()\n if you need to apply any modifications to the representation style.\n\n\nFor example:\n\n\ndef to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n\n\n\nDropping 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.\n\n\nIf you absolutely need to preserve \ntransform_\nfield_name\n 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:\n\n\nclass BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_\nfield_name\n` behavior.\n \"\"\"\n def to_representation(self, instance):\n ret = super(BaseModelSerializer, self).to_representation(instance)\n for key, value in ret.items():\n method = getattr(self, 'transform_' + key, None)\n if method is not None:\n ret[key] = method(value)\n return ret\n\n\n\nDifferences between ModelSerializer validation and ModelForm.\n\n\nThis change also means that we no longer use the \n.full_clean()\n 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 \nModelSerializer\n classes that can't also be easily replicated on regular \nSerializer\n classes.\n\n\nFor 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.\n\n\nThe one difference that you do need to note is that the \n.clean()\n method will not be called as part of serializer validation, as it would be if using a \nModelForm\n. Use the serializer \n.validate()\n method to perform a final validation step on incoming data where required.\n\n\nThere may be some cases where you really do need to keep validation logic in the model \n.clean()\n method, and cannot instead separate it into the serializer \n.validate()\n. You can do so by explicitly instantiating a model instance in the \n.validate()\n method.\n\n\ndef validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs\n\n\n\nAgain, 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.\n\n\nWritable nested serialization.\n\n\nREST 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:\n\n\n\n\nThere can be complex dependencies involved in order of saving multiple related model instances.\n\n\nIt's unclear what behavior the user should expect when related models are passed \nNone\n data.\n\n\nIt's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.\n\n\n\n\nUsing the \ndepth\n option on \nModelSerializer\n will now create \nread-only nested serializers\n by default.\n\n\nIf you try to use a writable nested serializer without writing a custom \ncreate()\n and/or \nupdate()\n method you'll see an assertion error when you attempt to save the serializer. For example:\n\n\n class ProfileSerializer(serializers.ModelSerializer):\n\n class Meta:\n\n model = Profile\n\n fields = ('address', 'phone')\n\n\n\n class UserSerializer(serializers.ModelSerializer):\n\n profile = ProfileSerializer()\n\n class Meta:\n\n model = User\n\n fields = ('username', 'email', 'profile')\n\n\n\n data = {\n\n 'username': 'lizzy',\n\n 'email': 'lizzy@example.com',\n\n 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n\n }\n\n\n\n serializer = UserSerializer(data=data)\n\n serializer.save()\nAssertionError: 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.\n\n\n\nTo use writable nested serialization you'll want to declare a nested field on the serializer class, and write the \ncreate()\n and/or \nupdate()\n methods explicitly.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n\n\n\nThe single-step object creation makes this far simpler and more obvious than the previous \n.restore_object()\n behavior.\n\n\nPrintable serializer representations.\n\n\nSerializer instances now support a printable representation that allows you to inspect the fields present on the instance.\n\n\nFor instance, given the following example model:\n\n\nclass LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User)\n\n\n\nLet's create a simple \nModelSerializer\n class corresponding to the \nLocationRating\n model.\n\n\nclass LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating\n\n\n\nWe can now inspect the serializer representation in the Django shell, using \npython manage.py shell\n...\n\n\n serializer = LocationRatingSerializer()\n\n print(serializer) # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n id = IntegerField(label='ID', read_only=True)\n location = CharField(max_length=100)\n rating = IntegerField()\n created_by = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nThe \nextra_kwargs\n option.\n\n\nThe \nwrite_only_fields\n option on \nModelSerializer\n has been moved to \nPendingDeprecation\n and replaced with a more generic \nextra_kwargs\n.\n\n\nclass MySerializer(serializer.ModelSerializer):\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'is_admin': {'write_only': True}\n }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.ModelSerializer):\n is_admin = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n\n\n\nThe \nread_only_fields\n option remains as a convenient shortcut for the more common case.\n\n\nChanges to \nHyperlinkedModelSerializer\n.\n\n\nThe \nview_name\n and \nlookup_field\n options have been moved to \nPendingDeprecation\n. They are no longer required, as you can use the \nextra_kwargs\n argument instead:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'url': {'lookup_field': 'uuid'}\n }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='mymodel-detail',\n lookup_field='uuid'\n )\n\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n\n\n\nFields for model methods and properties.\n\n\nWith \nModelSerializer\n you can now specify field names in the \nfields\n option that refer to model methods or properties. For example, suppose you have the following model:\n\n\nclass Invitation(models.Model):\n created = models.DateTimeField()\n to_email = models.EmailField()\n message = models.CharField(max_length=1000)\n\n def expiry_date(self):\n return self.created + datetime.timedelta(days=30)\n\n\n\nYou can include \nexpiry_date\n as a field option on a \nModelSerializer\n class.\n\n\nclass InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ('to_email', 'message', 'expiry_date')\n\n\n\nThese fields will be mapped to \nserializers.ReadOnlyField()\n instances.\n\n\n serializer = InvitationSerializer()\n\n print repr(serializer)\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()\n\n\n\nThe \nListSerializer\n class.\n\n\nThe \nListSerializer\n class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.\n\n\nclass MultipleUserSerializer(ListSerializer):\n child = UserSerializer()\n\n\n\nYou can also still use the \nmany=True\n argument to serializer classes. It's worth noting that \nmany=True\n argument transparently creates a \nListSerializer\n instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.\n\n\nYou will typically want to \ncontinue to use the existing \nmany=True\n flag\n rather than declaring \nListSerializer\n classes explicitly, but declaring the classes explicitly can be useful if you need to write custom \ncreate\n or \nupdate\n methods for bulk updates, or provide for other custom behavior.\n\n\nSee also the new \nListField\n class, which validates input in the same way, but does not include the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nBaseSerializer\n class.\n\n\nREST framework now includes a simple \nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns an errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n 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.\n\n\nRead-only \nBaseSerializer\n classes.\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes.\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) \n 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n\n\n\nCreating new generic serializers with \nBaseSerializer\n.\n\n\nThe \nBaseSerializer\n 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.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n\n\n\n\n\nSerializer fields\n\n\nReadOnly\n field classes.\nThe \nField\n and \n\n\nThere are some minor tweaks to the field base classes.\n\n\nPreviously we had these two base classes:\n\n\n\n\nField\n as the base class for read-only fields. A default implementation was included for serializing data.\n\n\nWritableField\n as the base class for read-write fields.\n\n\n\n\nWe now use the following:\n\n\n\n\nField\n is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.\n\n\nReadOnlyField\n is a concrete implementation for read-only fields that simply returns the attribute value without modification.\n\n\n\n\nallow_null\n, \ndefault\n arguments.\nThe \nrequired\n, \nallow_blank\n and \n\n\nREST framework now has more explicit and clear control over validating empty values for fields.\n\n\nPreviously the meaning of the \nrequired=False\n 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 \nNone\n or the empty string.\n\n\nWe now have a better separation, with separate \nrequired\n, \nallow_null\n and \nallow_blank\n arguments.\n\n\nThe following set of arguments are used to control validation of empty values:\n\n\n\n\nrequired=False\n: The value does not need to be present in the input, and will not be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\ndefault=\nvalue\n: The value does not need to be present in the input, and a default value will be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\nallow_null=True\n: \nNone\n is a valid input.\n\n\nallow_blank=True\n: \n''\n is valid input. For \nCharField\n and subclasses only.\n\n\n\n\nTypically you'll want to use \nrequired=False\n if the corresponding model field has a default value, and additionally set either \nallow_null=True\n or \nallow_blank=True\n if required.\n\n\nThe \ndefault\n argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the \nrequired\n argument when a default is specified, and doing so will result in an error.\n\n\nCoercing output types.\n\n\nThe previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an \nIntegerField\n 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.\n\n\nRemoval of \n.validate()\n.\n\n\nThe \n.validate()\n method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override \nto_internal_value()\n.\n\n\nclass UppercaseCharField(serializers.CharField):\n def to_internal_value(self, data):\n value = super(UppercaseCharField, self).to_internal_value(data)\n if value != value.upper():\n raise serializers.ValidationError('The input should be uppercase only.')\n return value\n\n\n\nPreviously validation errors could be raised in either \n.to_native()\n or \n.validate()\n, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.\n\n\nThe \nListField\n class.\n\n\nThe \nListField\n class has now been added. This field validates list input. It takes a \nchild\n keyword argument which is used to specify the field used to validate each item in the list. For example:\n\n\nscores = ListField(child=IntegerField(min_value=0, max_value=100))\n\n\n\nYou can also use a declarative style to create new subclasses of \nListField\n, like this:\n\n\nclass ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100)\n\n\n\nWe can now use the \nScoresField\n class inside another serializer:\n\n\nscores = ScoresField()\n\n\n\nSee also the new \nListSerializer\n class, which validates input in the same way, but also includes the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nChoiceField\n class may now accept a flat list.\n\n\nThe \nChoiceField\n class may now accept a list of choices in addition to the existing style of using a list of pairs of \n(name, display_value)\n. The following is now valid:\n\n\ncolor = ChoiceField(choices=['red', 'green', 'blue'])\n\n\n\nThe \nMultipleChoiceField\n class.\n\n\nThe \nMultipleChoiceField\n class has been added. This field acts like \nChoiceField\n, but returns a set, which may include none, one or many of the valid choices.\n\n\nChanges to the custom field API.\n\n\nThe \nfrom_native(self, value)\n and \nto_native(self, data)\n method names have been replaced with the more obviously named \nto_internal_value(self, data)\n and \nto_representation(self, value)\n.\n\n\nThe \nfield_from_native()\n and \nfield_to_native()\n 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...\n\n\ndef field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__\n\n\n\nNow if you need to access the entire object you'll instead need to override one or both of the following:\n\n\n\n\nUse \nget_attribute\n to modify the attribute value passed to \nto_representation()\n.\n\n\nUse \nget_value\n to modify the data value passed \nto_internal_value()\n.\n\n\n\n\nFor example:\n\n\ndef get_attribute(self, obj):\n # Pass the entire object through to `to_representation()`,\n # instead of the standard attribute lookup.\n return obj\n\ndef to_representation(self, value):\n return value.__class__.__name__\n\n\n\nExplicit \nqueryset\n required on relational fields.\n\n\nPreviously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a \nModelSerializer\n.\n\n\nThis code \nwould be valid\n in \n2.4.3\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account\n\n\n\nHowever this code \nwould not be valid\n in \n3.0\n:\n\n\n# Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ...\n\n\n\nThe queryset argument is now always required for writable relational fields.\nThis removes some magic and makes it easier and more obvious to move between implicit \nModelSerializer\n classes and explicit \nSerializer\n classes.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account\n\n\n\nThe \nqueryset\n argument is only ever required for writable fields, and is not required or valid for fields with \nread_only=True\n.\n\n\nOptional argument to \nSerializerMethodField\n.\n\n\nThe argument to \nSerializerMethodField\n is now optional, and defaults to \nget_\nfield_name\n. For example the following is valid:\n\n\nclass AccountSerializer(serializers.Serializer):\n # `method_name='get_billing_details'` by default.\n billing_details = serializers.SerializerMethodField()\n\n def get_billing_details(self, account):\n return calculate_billing(account)\n\n\n\nIn 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 \nwill raise an error\n:\n\n\nbilling_details = serializers.SerializerMethodField('get_billing_details')\n\n\n\nEnforcing consistent \nsource\n usage.\n\n\nI've see several codebases that unnecessarily include the \nsource\n argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that \nsource\n is usually not required.\n\n\nThe following usage will \nnow raise an error\n:\n\n\nemail = serializers.EmailField(source='email')\n\n\n\nUniqueTogetherValidator\n classes.\nThe \nUniqueValidator\n and \n\n\nREST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit \nSerializer\n class instead of using \nModelSerializer\n.\n\n\nThe \nUniqueValidator\n should be applied to a serializer field, and takes a single \nqueryset\n argument.\n\n\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n created = serializers.DateTimeField(read_only=True)\n name = serializers.CharField(\n max_length=100,\n validators=UniqueValidator(queryset=Organization.objects.all())\n )\n\n\n\nThe \nUniqueTogetherValidator\n should be applied to a serializer, and takes a \nqueryset\n argument and a \nfields\n argument which should be a list or tuple of field names.\n\n\nclass RaceResultSerializer(serializers.Serializer):\n category = serializers.ChoiceField(['5k', '10k'])\n position = serializers.IntegerField()\n name = serializers.CharField(max_length=100)\n\n class Meta:\n validators = [UniqueTogetherValidator(\n queryset=RaceResult.objects.all(),\n fields=('category', 'position')\n )]\n\n\n\nThe \nUniqueForDateValidator\n classes.\n\n\nREST framework also now includes explicit validator classes for validating the \nunique_for_date\n, \nunique_for_month\n, and \nunique_for_year\n model field constraints. These are used internally instead of calling into \nModel.full_clean()\n.\n\n\nThese classes are documented in the \nValidators\n section of the documentation.\n\n\n\n\nGeneric views\n\n\nSimplification of view logic.\n\n\nThe view logic for the default method handlers has been significantly simplified, due to the new serializers API.\n\n\nChanges to pre/post save hooks.\n\n\nThe \npre_save\n and \npost_save\n hooks no longer exist, but are replaced with \nperform_create(self, serializer)\n and \nperform_update(self, serializer)\n.\n\n\nThese methods should save the object instance by calling \nserializer.save()\n, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.\n\n\nFor example:\n\n\ndef perform_create(self, serializer):\n # Include the owner attribute directly, rather than from request data.\n instance = serializer.save(owner=self.request.user)\n # Perform a custom post-save action.\n send_email(instance.to_email, instance.message)\n\n\n\nThe \npre_delete\n and \npost_delete\n hooks no longer exist, and are replaced with \n.perform_destroy(self, instance)\n, which should delete the instance and perform any custom actions.\n\n\ndef perform_destroy(self, instance):\n # Perform a custom pre-delete action.\n send_deletion_alert(user=instance.created_by, deleted=instance)\n # Delete the object instance.\n instance.delete()\n\n\n\nRemoval of view attributes.\n\n\nThe \n.object\n and \n.object_list\n 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.\n\n\nI would personally recommend that developers treat view instances as immutable objects in their application code.\n\n\nPUT as create.\n\n\nAllowing \nPUT\n 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 \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n 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.\n\n\nIf you need to restore the previous behavior you may want to include \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\nCustomizing error responses.\n\n\nThe generic views now raise \nValidationFailed\n exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a \n400 Bad Request\n response directly.\n\n\nThis 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.\n\n\n\n\nThe metadata API\n\n\nBehavior for dealing with \nOPTIONS\n 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.\n\n\nThis makes it far easier to use a different style for \nOPTIONS\n responses throughout your API, and makes it possible to create third-party metadata policies.\n\n\n\n\nSerializers as HTML forms\n\n\nREST framework 3.0 includes templated HTML form rendering for serializers.\n\n\nThis API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.\n\n\nSignificant changes that you do need to be aware of include:\n\n\n\n\nNested HTML forms are now supported, for example, a \nUserSerializer\n with a nested \nProfileSerializer\n will now render a nested \nfieldset\n when used in the browsable API.\n\n\nNested lists of HTML forms are not yet supported, but are planned for 3.1.\n\n\nBecause we now use templated HTML form generation, \nthe \nwidget\n option is no longer available for serializer fields\n. You can instead control the template that is used for a given field, by using the \nstyle\n dictionary.\n\n\n\n\nThe \nstyle\n keyword argument for serializer fields.\n\n\nThe \nstyle\n keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the \nHTMLFormRenderer\n uses the \nbase_template\n key to determine which template to render the field with.\n\n\nFor example, to use a \ntextarea\n control instead of the default \ninput\n control, you would use the following\u2026\n\n\nadditional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n)\n\n\n\nSimilarly, to use a radio button control instead of the default \nselect\n control, you would use the following\u2026\n\n\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n)\n\n\n\nThis API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.\n\n\n\n\nAPI style\n\n\nThere are some improvements in the default style we use in our API responses.\n\n\nUnicode JSON by default.\n\n\nUnicode JSON is now the default. The \nUnicodeJSONRenderer\n class no longer exists, and the \nUNICODE_JSON\n setting has been added. To revert this behavior use the new setting:\n\n\nREST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}\n\n\n\nCompact JSON by default.\n\n\nWe now output compact JSON in responses by default. For example, we return:\n\n\n{\"email\":\"amy@example.com\",\"is_admin\":true}\n\n\n\nInstead of the following:\n\n\n{\"email\": \"amy@example.com\", \"is_admin\": true}\n\n\n\nThe \nCOMPACT_JSON\n setting has been added, and can be used to revert this behavior if needed:\n\n\nREST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}\n\n\n\nFile fields as URLs\n\n\nThe \nFileField\n and \nImageField\n classes are now represented as URLs by default. You should ensure you set Django's \nstandard \nMEDIA_URL\n setting\n appropriately, and ensure your application \nserves the uploaded files\n.\n\n\nYou can revert this behavior, and display filenames in the representation by using the \nUPLOADED_FILES_USE_URL\n settings key:\n\n\nREST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n}\n\n\n\nYou can also modify serializer fields individually, using the \nuse_url\n argument:\n\n\nuploaded_file = serializers.FileField(use_url=False)\n\n\n\nAlso note that you should pass the \nrequest\n 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 \nhttps://example.com/url_path/filename.txt\n. For example:\n\n\ncontext = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data)\n\n\n\nIf the request is omitted from the context, the returned URLs will be of the form \n/url_path/filename.txt\n.\n\n\nThrottle headers using \nRetry-After\n.\n\n\nThe custom \nX-Throttle-Wait-Second\n header has now been dropped in favor of the standard \nRetry-After\n header. You can revert this behavior if needed by writing a custom exception handler for your application.\n\n\nDate and time objects as ISO-8859-1 strings in serializer data.\n\n\nDate and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as \nDate\n, \nTime\n and \nDateTime\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by settings the existing \nDATE_FORMAT\n, \nDATETIME_FORMAT\n and \nTIME_FORMAT\n settings keys. Setting these values to \nNone\n instead of their default value of \n'iso-8859-1'\n will result in native objects being returned in serializer data.\n\n\nREST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n}\n\n\n\nYou can also modify serializer fields individually, using the \ndate_format\n, \ntime_format\n and \ndatetime_format\n arguments:\n\n\n# Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)\n\n\n\nDecimals as strings in serializer data.\n\n\nDecimals are now coerced to strings by default in the serializer output. Previously they were returned as \nDecimal\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by using the \nCOERCE_DECIMAL_TO_STRING\n settings key.\n\n\nREST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n}\n\n\n\nOr modify it on an individual serializer field, using the \ncoerce_to_string\n keyword argument.\n\n\n# Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n max_digits=10,\n decimal_places=2,\n coerce_to_string=False\n)\n\n\n\nThe default JSON renderer will return float objects for un-coerced \nDecimal\n instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.\n\n\n\n\nMiscellaneous notes\n\n\n\n\nThe serializer \nChoiceField\n does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.\n\n\nDue 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.\n\n\nSome of the default validation error messages were rewritten and might no longer be pre-translated. You can still \ncreate language files with Django\n if you wish to localize them.\n\n\nAPIException\n subclasses could previously take any arbitrary type in the \ndetail\n argument. These exceptions now use translatable text strings, and as a result call \nforce_text\n on the \ndetail\n argument, which \nmust be a string\n. If you need complex arguments to an \nAPIException\n class, you should subclass it and override the \n__init__()\n method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.\n\n\n\n\n\n\nWhat's coming next\n\n\n3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.\n\n\nThe 3.1 release is planned to address improvements in the following components:\n\n\n\n\nPublic API for using serializers as HTML forms.\n\n\nRequest parsing, mediatypes \n the implementation of the browsable API.\n\n\nIntroduction of a new pagination API.\n\n\nBetter support for API versioning.\n\n\n\n\nThe 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.\n\n\nYou can follow development on the GitHub site, where we use \nmilestones to indicate planning timescales\n.",
"title": "3.0 Announcement"
},
{
@@ -2932,29 +4142,219 @@
},
{
"location": "/topics/3.0-announcement/#new-features",
- "text": "Notable features of this new release include: Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit ModelSerializer class and the explicit Serializer class. A new BaseSerializer class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. A cleaner fields API including new classes such as ListField and MultipleChoiceField . Super simple default implementations for the generic views. Support for overriding how validation errors are handled by your API. A metadata API that allows you to customize how OPTIONS requests are handled by your API. A more compact JSON output with unicode style encoding turned on by default. Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release. Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - \"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. REST framework: Under the hood. This talk from the Django: Under the Hood event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0. Below is an in-depth guide to the API changes and migration notes for 3.0.",
+ "text": "Notable features of this new release include: Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit ModelSerializer class and the explicit Serializer class. A new BaseSerializer class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. A cleaner fields API including new classes such as ListField and MultipleChoiceField . Super simple default implementations for the generic views. Support for overriding how validation errors are handled by your API. A metadata API that allows you to customize how OPTIONS requests are handled by your API. A more compact JSON output with unicode style encoding turned on by default. Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release. Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - \"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.",
"title": "New features"
},
+ {
+ "location": "/topics/3.0-announcement/#rest-framework-under-the-hood",
+ "text": "This talk from the Django: Under the Hood event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0. Below is an in-depth guide to the API changes and migration notes for 3.0.",
+ "title": "REST framework: Under the hood."
+ },
{
"location": "/topics/3.0-announcement/#request-objects",
- "text": "The .data and .query_params properties. The usage of request.DATA and request.FILES is now pending deprecation in favor of a single request.data attribute that contains all the parsed data. 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. You may now pass all the request data to a serializer class in a single argument: # Do this...\nExampleSerializer(data=request.data) Instead of passing the files argument separately: # Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES) The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params .",
+ "text": "",
"title": "Request objects"
},
+ {
+ "location": "/topics/3.0-announcement/#the-data-and-query_params-properties",
+ "text": "The usage of request.DATA and request.FILES is now pending deprecation in favor of a single request.data attribute that contains all the parsed data. 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. You may now pass all the request data to a serializer class in a single argument: # Do this...\nExampleSerializer(data=request.data) Instead of passing the files argument separately: # Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES) The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params .",
+ "title": "The .data and .query_params properties."
+ },
{
"location": "/topics/3.0-announcement/#serializers",
- "text": "Single-step object creation. Previously the serializers used a two-step object creation, as follows: Validating the data would create an object instance. This instance would be available as serializer.object . Calling serializer.save() would then save the object instance to the database. This style is in-line with how the ModelForm class works in Django, but is problematic for a number of reasons: 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 .save() is called. Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. ExampleModel.objects.create(...) . Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. 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? We now use single-step object creation, like so: Validating the data makes the cleaned data available as serializer.validated_data . Calling serializer.save() then saves and returns the new object instance. The resulting API changes are further detailed below. The .create() and .update() methods. The .restore_object() method is now removed, and we instead have two separate methods, .create() and .update() . These methods work slightly different to the previous .restore_object() . When using the .create() and .update() methods you should both create and save the object instance. This is in contrast to the previous .restore_object() behavior that would instantiate the object but not save it. These methods also replace the optional .save_object() method, which no longer exists. The following example from the tutorial previously used restore_object() to handle both creating and updating object instances. def restore_object(self, attrs, instance=None):\n if instance:\n # Update existing instance\n instance.title = attrs.get('title', instance.title)\n instance.code = attrs.get('code', instance.code)\n instance.linenos = attrs.get('linenos', instance.linenos)\n instance.language = attrs.get('language', instance.language)\n instance.style = attrs.get('style', instance.style)\n return instance\n\n # Create new instance\n return Snippet(**attrs) This would now be split out into two separate methods. def update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\ndef create(self, validated_data):\n return Snippet.objects.create(**validated_data) Note that these methods should return the newly created object instance. Use .validated_data instead of .object . You must now use the .validated_data attribute if you need to inspect the data before saving, rather than using the .object attribute, which no longer exists. For example the following code is no longer valid : if serializer.is_valid():\n name = serializer.object.name # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.object.user = request.user # Include the user when saving.\n serializer.save() Instead of using .object to inspect a partially constructed instance, you would now use .validated_data to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the .save() method as keyword arguments. The corresponding code would now look like this: if serializer.is_valid():\n name = serializer.validated_data['name'] # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.save(user=request.user) # Include the user when saving. Using .is_valid(raise_exception=True) The .is_valid() method now takes an optional boolean flag, raise_exception . Calling .is_valid(raise_exception=True) will cause a ValidationError 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. The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key. 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. Using serializers.ValidationError . Previously serializers.ValidationError error was simply a synonym for django.core.exceptions.ValidationError . This has now been altered so that it inherits from the standard APIException base class. The reason behind this is that Django's ValidationError 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. 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 serializers.ValidationError exception class, and not Django's built-in exception. We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion. Change to validate_ field_name . The validate_ field_name 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: def validate_score(self, attrs, source):\n if attrs['score'] % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return attrs This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value. def validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value Any ad-hoc validation that applies to more than one field should go in the .validate(self, attrs) method as usual. Because .validate_ field_name 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 .validate() instead. You can either return non_field_errors from the validate method by raising a simple ValidationError def validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error') Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError , like so: def validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'}) This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field. Removal of transform_ field_name . The under-used transform_ field_name on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style. For example: def to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret 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. If you absolutely need to preserve transform_ field_name 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: class BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_ field_name ` behavior.\n \"\"\"\n def to_representation(self, instance):\n ret = super(BaseModelSerializer, self).to_representation(instance)\n for key, value in ret.items():\n method = getattr(self, 'transform_' + key, None)\n if method is not None:\n ret[key] = method(value)\n return ret Differences between ModelSerializer validation and ModelForm. This change also means that we no longer use the .full_clean() 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 ModelSerializer classes that can't also be easily replicated on regular Serializer classes. 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. The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm . Use the serializer .validate() method to perform a final validation step on incoming data where required. There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate() . You can do so by explicitly instantiating a model instance in the .validate() method. def validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs 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. Writable nested serialization. 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: There can be complex dependencies involved in order of saving multiple related model instances. It's unclear what behavior the user should expect when related models are passed None data. It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. Using the depth option on ModelSerializer will now create read-only nested serializers by default. If you try to use a writable nested serializer without writing a custom create() and/or update() method you'll see an assertion error when you attempt to save the serializer. For example: 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()\nAssertionError: 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. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly. class UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior. Printable serializer representations. Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. For instance, given the following example model: class LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User) Let's create a simple ModelSerializer class corresponding to the LocationRating model. class LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating We can now inspect the serializer representation in the Django shell, using python manage.py shell ... serializer = LocationRatingSerializer() print(serializer) # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n id = IntegerField(label='ID', read_only=True)\n location = CharField(max_length=100)\n rating = IntegerField()\n created_by = PrimaryKeyRelatedField(queryset=User.objects.all()) The extra_kwargs option. The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs . class MySerializer(serializer.ModelSerializer):\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'is_admin': {'write_only': True}\n } Alternatively, specify the field explicitly on the serializer class: class MySerializer(serializer.ModelSerializer):\n is_admin = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin') The read_only_fields option remains as a convenient shortcut for the more common case. Changes to HyperlinkedModelSerializer . The view_name and lookup_field options have been moved to PendingDeprecation . They are no longer required, as you can use the extra_kwargs argument instead: class MySerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'url': {'lookup_field': 'uuid'}\n } Alternatively, specify the field explicitly on the serializer class: class MySerializer(serializer.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='mymodel-detail',\n lookup_field='uuid'\n )\n\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin') Fields for model methods and properties. With ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model: class Invitation(models.Model):\n created = models.DateTimeField()\n to_email = models.EmailField()\n message = models.CharField(max_length=1000)\n\n def expiry_date(self):\n return self.created + datetime.timedelta(days=30) You can include expiry_date as a field option on a ModelSerializer class. class InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ('to_email', 'message', 'expiry_date') These fields will be mapped to serializers.ReadOnlyField() instances. serializer = InvitationSerializer() print repr(serializer)\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField() The ListSerializer class. The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs. class MultipleUserSerializer(ListSerializer):\n child = UserSerializer() You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior. See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid() , .data , .save() and so on. The BaseSerializer class. REST framework now includes a simple BaseSerializer class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the Serializer class: .data - Returns the outgoing primitive representation. .is_valid() - Deserializes and validates incoming data. .validated_data - Returns the validated incoming data. .errors - Returns an errors during validation. .save() - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: .to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations. .create() and .update() - Override either or both of these to support saving instances. Because this class provides the same interface as the Serializer class, you can use it with the existing generic class based views exactly as you would for a regular Serializer or ModelSerializer . The only difference you'll notice when doing so is the BaseSerializer 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. Read-only BaseSerializer classes. To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model: class HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField() It's simple to create a read-only serializer for converting HighScore instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n } We can now use this class to serialize single HighScore instances: @api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data) Or use it to serialize multiple instances: @api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data) Read-write BaseSerializer classes. To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format. Once you've implemented .to_internal_value() , the basic validation API will be available on the serializer, and you will be able to use .is_valid() , .validated_data and .errors . If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods. Here's a complete example of our previous HighScoreSerializer , that's been updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data) Creating new generic serializers with BaseSerializer . The BaseSerializer 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. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)",
+ "text": "",
"title": "Serializers"
},
+ {
+ "location": "/topics/3.0-announcement/#single-step-object-creation",
+ "text": "Previously the serializers used a two-step object creation, as follows: Validating the data would create an object instance. This instance would be available as serializer.object . Calling serializer.save() would then save the object instance to the database. This style is in-line with how the ModelForm class works in Django, but is problematic for a number of reasons: 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 .save() is called. Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. ExampleModel.objects.create(...) . Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. 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? We now use single-step object creation, like so: Validating the data makes the cleaned data available as serializer.validated_data . Calling serializer.save() then saves and returns the new object instance. The resulting API changes are further detailed below.",
+ "title": "Single-step object creation."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-create-and-update-methods",
+ "text": "The .restore_object() method is now removed, and we instead have two separate methods, .create() and .update() . These methods work slightly different to the previous .restore_object() . When using the .create() and .update() methods you should both create and save the object instance. This is in contrast to the previous .restore_object() behavior that would instantiate the object but not save it. These methods also replace the optional .save_object() method, which no longer exists. The following example from the tutorial previously used restore_object() to handle both creating and updating object instances. def restore_object(self, attrs, instance=None):\n if instance:\n # Update existing instance\n instance.title = attrs.get('title', instance.title)\n instance.code = attrs.get('code', instance.code)\n instance.linenos = attrs.get('linenos', instance.linenos)\n instance.language = attrs.get('language', instance.language)\n instance.style = attrs.get('style', instance.style)\n return instance\n\n # Create new instance\n return Snippet(**attrs) This would now be split out into two separate methods. def update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\ndef create(self, validated_data):\n return Snippet.objects.create(**validated_data) Note that these methods should return the newly created object instance.",
+ "title": "The .create() and .update() methods."
+ },
+ {
+ "location": "/topics/3.0-announcement/#use-validated_data-instead-of-object",
+ "text": "You must now use the .validated_data attribute if you need to inspect the data before saving, rather than using the .object attribute, which no longer exists. For example the following code is no longer valid : if serializer.is_valid():\n name = serializer.object.name # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.object.user = request.user # Include the user when saving.\n serializer.save() Instead of using .object to inspect a partially constructed instance, you would now use .validated_data to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the .save() method as keyword arguments. The corresponding code would now look like this: if serializer.is_valid():\n name = serializer.validated_data['name'] # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.save(user=request.user) # Include the user when saving.",
+ "title": "Use .validated_data instead of .object."
+ },
+ {
+ "location": "/topics/3.0-announcement/#using-is_validraise_exceptiontrue",
+ "text": "The .is_valid() method now takes an optional boolean flag, raise_exception . Calling .is_valid(raise_exception=True) will cause a ValidationError 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. The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key. 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.",
+ "title": "Using .is_valid(raise_exception=True)"
+ },
+ {
+ "location": "/topics/3.0-announcement/#using-serializersvalidationerror",
+ "text": "Previously serializers.ValidationError error was simply a synonym for django.core.exceptions.ValidationError . This has now been altered so that it inherits from the standard APIException base class. The reason behind this is that Django's ValidationError 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. 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 serializers.ValidationError exception class, and not Django's built-in exception. We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion.",
+ "title": "Using serializers.ValidationError."
+ },
+ {
+ "location": "/topics/3.0-announcement/#change-to-validate_field_name",
+ "text": "The validate_ field_name 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: def validate_score(self, attrs, source):\n if attrs['score'] % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return attrs This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value. def validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value Any ad-hoc validation that applies to more than one field should go in the .validate(self, attrs) method as usual. Because .validate_ field_name 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 .validate() instead. You can either return non_field_errors from the validate method by raising a simple ValidationError def validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error') Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError , like so: def validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'}) This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.",
+ "title": "Change to validate_<field_name>."
+ },
+ {
+ "location": "/topics/3.0-announcement/#removal-of-transform_field_name",
+ "text": "The under-used transform_ field_name on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style. For example: def to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret 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. If you absolutely need to preserve transform_ field_name 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: class BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_ field_name ` behavior.\n \"\"\"\n def to_representation(self, instance):\n ret = super(BaseModelSerializer, self).to_representation(instance)\n for key, value in ret.items():\n method = getattr(self, 'transform_' + key, None)\n if method is not None:\n ret[key] = method(value)\n return ret",
+ "title": "Removal of transform_<field_name>."
+ },
+ {
+ "location": "/topics/3.0-announcement/#differences-between-modelserializer-validation-and-modelform",
+ "text": "This change also means that we no longer use the .full_clean() 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 ModelSerializer classes that can't also be easily replicated on regular Serializer classes. 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. The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm . Use the serializer .validate() method to perform a final validation step on incoming data where required. There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate() . You can do so by explicitly instantiating a model instance in the .validate() method. def validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs 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.",
+ "title": "Differences between ModelSerializer validation and ModelForm."
+ },
+ {
+ "location": "/topics/3.0-announcement/#writable-nested-serialization",
+ "text": "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: There can be complex dependencies involved in order of saving multiple related model instances. It's unclear what behavior the user should expect when related models are passed None data. It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. Using the depth option on ModelSerializer will now create read-only nested serializers by default. If you try to use a writable nested serializer without writing a custom create() and/or update() method you'll see an assertion error when you attempt to save the serializer. For example: 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()\nAssertionError: 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. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly. class UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior.",
+ "title": "Writable nested serialization."
+ },
+ {
+ "location": "/topics/3.0-announcement/#printable-serializer-representations",
+ "text": "Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. For instance, given the following example model: class LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User) Let's create a simple ModelSerializer class corresponding to the LocationRating model. class LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating We can now inspect the serializer representation in the Django shell, using python manage.py shell ... serializer = LocationRatingSerializer() print(serializer) # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n id = IntegerField(label='ID', read_only=True)\n location = CharField(max_length=100)\n rating = IntegerField()\n created_by = PrimaryKeyRelatedField(queryset=User.objects.all())",
+ "title": "Printable serializer representations."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-extra_kwargs-option",
+ "text": "The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs . class MySerializer(serializer.ModelSerializer):\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'is_admin': {'write_only': True}\n } Alternatively, specify the field explicitly on the serializer class: class MySerializer(serializer.ModelSerializer):\n is_admin = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin') The read_only_fields option remains as a convenient shortcut for the more common case.",
+ "title": "The extra_kwargs option."
+ },
+ {
+ "location": "/topics/3.0-announcement/#changes-to-hyperlinkedmodelserializer",
+ "text": "The view_name and lookup_field options have been moved to PendingDeprecation . They are no longer required, as you can use the extra_kwargs argument instead: class MySerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'url': {'lookup_field': 'uuid'}\n } Alternatively, specify the field explicitly on the serializer class: class MySerializer(serializer.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='mymodel-detail',\n lookup_field='uuid'\n )\n\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')",
+ "title": "Changes to HyperlinkedModelSerializer."
+ },
+ {
+ "location": "/topics/3.0-announcement/#fields-for-model-methods-and-properties",
+ "text": "With ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model: class Invitation(models.Model):\n created = models.DateTimeField()\n to_email = models.EmailField()\n message = models.CharField(max_length=1000)\n\n def expiry_date(self):\n return self.created + datetime.timedelta(days=30) You can include expiry_date as a field option on a ModelSerializer class. class InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ('to_email', 'message', 'expiry_date') These fields will be mapped to serializers.ReadOnlyField() instances. serializer = InvitationSerializer() print repr(serializer)\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()",
+ "title": "Fields for model methods and properties."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-listserializer-class",
+ "text": "The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs. class MultipleUserSerializer(ListSerializer):\n child = UserSerializer() You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior. See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid() , .data , .save() and so on.",
+ "title": "The ListSerializer class."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-baseserializer-class",
+ "text": "REST framework now includes a simple BaseSerializer class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the Serializer class: .data - Returns the outgoing primitive representation. .is_valid() - Deserializes and validates incoming data. .validated_data - Returns the validated incoming data. .errors - Returns an errors during validation. .save() - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: .to_representation() - Override this to support serialization, for read operations. .to_internal_value() - Override this to support deserialization, for write operations. .create() and .update() - Override either or both of these to support saving instances. Because this class provides the same interface as the Serializer class, you can use it with the existing generic class based views exactly as you would for a regular Serializer or ModelSerializer . The only difference you'll notice when doing so is the BaseSerializer 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.",
+ "title": "The BaseSerializer class."
+ },
+ {
+ "location": "/topics/3.0-announcement/#read-only-baseserializer-classes",
+ "text": "To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model: class HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField() It's simple to create a read-only serializer for converting HighScore instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n } We can now use this class to serialize single HighScore instances: @api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data) Or use it to serialize multiple instances: @api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)",
+ "title": "Read-only BaseSerializer classes."
+ },
+ {
+ "location": "/topics/3.0-announcement/#read-write-baseserializer-classes",
+ "text": "To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format. Once you've implemented .to_internal_value() , the basic validation API will be available on the serializer, and you will be able to use .is_valid() , .validated_data and .errors . If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods. Here's a complete example of our previous HighScoreSerializer , that's been updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)",
+ "title": "Read-write BaseSerializer classes."
+ },
+ {
+ "location": "/topics/3.0-announcement/#creating-new-generic-serializers-with-baseserializer",
+ "text": "The BaseSerializer 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. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)",
+ "title": "Creating new generic serializers with BaseSerializer."
+ },
{
"location": "/topics/3.0-announcement/#serializer-fields",
- "text": "The Field and ReadOnly field classes. There are some minor tweaks to the field base classes. Previously we had these two base classes: Field as the base class for read-only fields. A default implementation was included for serializing data. WritableField as the base class for read-write fields. We now use the following: Field is the base class for all fields. It does not include any default implementation for either serializing or deserializing data. ReadOnlyField is a concrete implementation for read-only fields that simply returns the attribute value without modification. The required , allow_null , allow_blank and default arguments. REST framework now has more explicit and clear control over validating empty values for fields. Previously the meaning of the required=False 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 None or the empty string. We now have a better separation, with separate required , allow_null and allow_blank arguments. The following set of arguments are used to control validation of empty values: required=False : The value does not need to be present in the input, and will not be passed to .create() or .update() if it is not seen. default= value : The value does not need to be present in the input, and a default value will be passed to .create() or .update() if it is not seen. allow_null=True : None is a valid input. allow_blank=True : '' is valid input. For CharField and subclasses only. Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_null=True or allow_blank=True if required. The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error. Coercing output types. The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an IntegerField 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. Removal of .validate() . The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value() . class UppercaseCharField(serializers.CharField):\n def to_internal_value(self, data):\n value = super(UppercaseCharField, self).to_internal_value(data)\n if value != value.upper():\n raise serializers.ValidationError('The input should be uppercase only.')\n return value Previously validation errors could be raised in either .to_native() or .validate() , making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API. The ListField class. The ListField class has now been added. This field validates list input. It takes a child keyword argument which is used to specify the field used to validate each item in the list. For example: scores = ListField(child=IntegerField(min_value=0, max_value=100)) You can also use a declarative style to create new subclasses of ListField , like this: class ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100) We can now use the ScoresField class inside another serializer: scores = ScoresField() See also the new ListSerializer class, which validates input in the same way, but also includes the serializer interfaces of .is_valid() , .data , .save() and so on. The ChoiceField class may now accept a flat list. The ChoiceField class may now accept a list of choices in addition to the existing style of using a list of pairs of (name, display_value) . The following is now valid: color = ChoiceField(choices=['red', 'green', 'blue']) The MultipleChoiceField class. The MultipleChoiceField class has been added. This field acts like ChoiceField , but returns a set, which may include none, one or many of the valid choices. Changes to the custom field API. The from_native(self, value) and to_native(self, data) method names have been replaced with the more obviously named to_internal_value(self, data) and to_representation(self, value) . The field_from_native() and field_to_native() 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... def field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__ Now if you need to access the entire object you'll instead need to override one or both of the following: Use get_attribute to modify the attribute value passed to to_representation() . Use get_value to modify the data value passed to_internal_value() . For example: def get_attribute(self, obj):\n # Pass the entire object through to `to_representation()`,\n # instead of the standard attribute lookup.\n return obj\n\ndef to_representation(self, value):\n return value.__class__.__name__ Explicit queryset required on relational fields. 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 ModelSerializer . This code would be valid in 2.4.3 : class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account However this code would not be valid in 3.0 : # Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ... The queryset argument is now always required for writable relational fields.\nThis removes some magic and makes it easier and more obvious to move between implicit ModelSerializer classes and explicit Serializer classes. class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True . Optional argument to SerializerMethodField . The argument to SerializerMethodField is now optional, and defaults to get_ field_name . For example the following is valid: class AccountSerializer(serializers.Serializer):\n # `method_name='get_billing_details'` by default.\n billing_details = serializers.SerializerMethodField()\n\n def get_billing_details(self, account):\n return calculate_billing(account) 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 will raise an error : billing_details = serializers.SerializerMethodField('get_billing_details') Enforcing consistent source usage. I've see several codebases that unnecessarily include the source argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that source is usually not required. The following usage will now raise an error : email = serializers.EmailField(source='email') The UniqueValidator and UniqueTogetherValidator classes. REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit Serializer class instead of using ModelSerializer . The UniqueValidator should be applied to a serializer field, and takes a single queryset argument. from rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n created = serializers.DateTimeField(read_only=True)\n name = serializers.CharField(\n max_length=100,\n validators=UniqueValidator(queryset=Organization.objects.all())\n ) The UniqueTogetherValidator should be applied to a serializer, and takes a queryset argument and a fields argument which should be a list or tuple of field names. class RaceResultSerializer(serializers.Serializer):\n category = serializers.ChoiceField(['5k', '10k'])\n position = serializers.IntegerField()\n name = serializers.CharField(max_length=100)\n\n class Meta:\n validators = [UniqueTogetherValidator(\n queryset=RaceResult.objects.all(),\n fields=('category', 'position')\n )] The UniqueForDateValidator classes. REST framework also now includes explicit validator classes for validating the unique_for_date , unique_for_month , and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean() . These classes are documented in the Validators section of the documentation.",
+ "text": "",
"title": "Serializer fields"
},
+ {
+ "location": "/topics/3.0-announcement/#the-field-and-readonly-field-classes",
+ "text": "There are some minor tweaks to the field base classes. Previously we had these two base classes: Field as the base class for read-only fields. A default implementation was included for serializing data. WritableField as the base class for read-write fields. We now use the following: Field is the base class for all fields. It does not include any default implementation for either serializing or deserializing data. ReadOnlyField is a concrete implementation for read-only fields that simply returns the attribute value without modification.",
+ "title": "The Field and ReadOnly field classes."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-required-allow_null-allow_blank-and-default-arguments",
+ "text": "REST framework now has more explicit and clear control over validating empty values for fields. Previously the meaning of the required=False 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 None or the empty string. We now have a better separation, with separate required , allow_null and allow_blank arguments. The following set of arguments are used to control validation of empty values: required=False : The value does not need to be present in the input, and will not be passed to .create() or .update() if it is not seen. default= value : The value does not need to be present in the input, and a default value will be passed to .create() or .update() if it is not seen. allow_null=True : None is a valid input. allow_blank=True : '' is valid input. For CharField and subclasses only. Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_null=True or allow_blank=True if required. The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error.",
+ "title": "The required, allow_null, allow_blank and default arguments."
+ },
+ {
+ "location": "/topics/3.0-announcement/#coercing-output-types",
+ "text": "The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an IntegerField 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.",
+ "title": "Coercing output types."
+ },
+ {
+ "location": "/topics/3.0-announcement/#removal-of-validate",
+ "text": "The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value() . class UppercaseCharField(serializers.CharField):\n def to_internal_value(self, data):\n value = super(UppercaseCharField, self).to_internal_value(data)\n if value != value.upper():\n raise serializers.ValidationError('The input should be uppercase only.')\n return value Previously validation errors could be raised in either .to_native() or .validate() , making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.",
+ "title": "Removal of .validate()."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-listfield-class",
+ "text": "The ListField class has now been added. This field validates list input. It takes a child keyword argument which is used to specify the field used to validate each item in the list. For example: scores = ListField(child=IntegerField(min_value=0, max_value=100)) You can also use a declarative style to create new subclasses of ListField , like this: class ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100) We can now use the ScoresField class inside another serializer: scores = ScoresField() See also the new ListSerializer class, which validates input in the same way, but also includes the serializer interfaces of .is_valid() , .data , .save() and so on.",
+ "title": "The ListField class."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-choicefield-class-may-now-accept-a-flat-list",
+ "text": "The ChoiceField class may now accept a list of choices in addition to the existing style of using a list of pairs of (name, display_value) . The following is now valid: color = ChoiceField(choices=['red', 'green', 'blue'])",
+ "title": "The ChoiceField class may now accept a flat list."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-multiplechoicefield-class",
+ "text": "The MultipleChoiceField class has been added. This field acts like ChoiceField , but returns a set, which may include none, one or many of the valid choices.",
+ "title": "The MultipleChoiceField class."
+ },
+ {
+ "location": "/topics/3.0-announcement/#changes-to-the-custom-field-api",
+ "text": "The from_native(self, value) and to_native(self, data) method names have been replaced with the more obviously named to_internal_value(self, data) and to_representation(self, value) . The field_from_native() and field_to_native() 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... def field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__ Now if you need to access the entire object you'll instead need to override one or both of the following: Use get_attribute to modify the attribute value passed to to_representation() . Use get_value to modify the data value passed to_internal_value() . For example: def get_attribute(self, obj):\n # Pass the entire object through to `to_representation()`,\n # instead of the standard attribute lookup.\n return obj\n\ndef to_representation(self, value):\n return value.__class__.__name__",
+ "title": "Changes to the custom field API."
+ },
+ {
+ "location": "/topics/3.0-announcement/#explicit-queryset-required-on-relational-fields",
+ "text": "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 ModelSerializer . This code would be valid in 2.4.3 : class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account However this code would not be valid in 3.0 : # Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ... The queryset argument is now always required for writable relational fields.\nThis removes some magic and makes it easier and more obvious to move between implicit ModelSerializer classes and explicit Serializer classes. class AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True .",
+ "title": "Explicit queryset required on relational fields."
+ },
+ {
+ "location": "/topics/3.0-announcement/#optional-argument-to-serializermethodfield",
+ "text": "The argument to SerializerMethodField is now optional, and defaults to get_ field_name . For example the following is valid: class AccountSerializer(serializers.Serializer):\n # `method_name='get_billing_details'` by default.\n billing_details = serializers.SerializerMethodField()\n\n def get_billing_details(self, account):\n return calculate_billing(account) 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 will raise an error : billing_details = serializers.SerializerMethodField('get_billing_details')",
+ "title": "Optional argument to SerializerMethodField."
+ },
+ {
+ "location": "/topics/3.0-announcement/#enforcing-consistent-source-usage",
+ "text": "I've see several codebases that unnecessarily include the source argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that source is usually not required. The following usage will now raise an error : email = serializers.EmailField(source='email')",
+ "title": "Enforcing consistent source usage."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-uniquevalidator-and-uniquetogethervalidator-classes",
+ "text": "REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit Serializer class instead of using ModelSerializer . The UniqueValidator should be applied to a serializer field, and takes a single queryset argument. from rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n created = serializers.DateTimeField(read_only=True)\n name = serializers.CharField(\n max_length=100,\n validators=UniqueValidator(queryset=Organization.objects.all())\n ) The UniqueTogetherValidator should be applied to a serializer, and takes a queryset argument and a fields argument which should be a list or tuple of field names. class RaceResultSerializer(serializers.Serializer):\n category = serializers.ChoiceField(['5k', '10k'])\n position = serializers.IntegerField()\n name = serializers.CharField(max_length=100)\n\n class Meta:\n validators = [UniqueTogetherValidator(\n queryset=RaceResult.objects.all(),\n fields=('category', 'position')\n )]",
+ "title": "The UniqueValidator and UniqueTogetherValidator classes."
+ },
+ {
+ "location": "/topics/3.0-announcement/#the-uniquefordatevalidator-classes",
+ "text": "REST framework also now includes explicit validator classes for validating the unique_for_date , unique_for_month , and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean() . These classes are documented in the Validators section of the documentation.",
+ "title": "The UniqueForDateValidator classes."
+ },
{
"location": "/topics/3.0-announcement/#generic-views",
- "text": "Simplification of view logic. The view logic for the default method handlers has been significantly simplified, due to the new serializers API. Changes to pre/post save hooks. The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer) . These methods should save the object instance by calling serializer.save() , adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior. For example: def perform_create(self, serializer):\n # Include the owner attribute directly, rather than from request data.\n instance = serializer.save(owner=self.request.user)\n # Perform a custom post-save action.\n send_email(instance.to_email, instance.message) The pre_delete and post_delete hooks no longer exist, and are replaced with .perform_destroy(self, instance) , which should delete the instance and perform any custom actions. def perform_destroy(self, instance):\n # Perform a custom pre-delete action.\n send_deletion_alert(user=instance.created_by, deleted=instance)\n # Delete the object instance.\n instance.delete() Removal of view attributes. The .object and .object_list 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. I would personally recommend that developers treat view instances as immutable objects in their application code. PUT as create. Allowing PUT 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 404 responses. Both styles \" PUT as 404\" and \" PUT 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. If you need to restore the previous behavior you may want to include this AllowPUTAsCreateMixin class as a mixin to your views. Customizing error responses. The generic views now raise ValidationFailed exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a 400 Bad Request response directly. 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.",
+ "text": "",
"title": "Generic views"
},
+ {
+ "location": "/topics/3.0-announcement/#simplification-of-view-logic",
+ "text": "The view logic for the default method handlers has been significantly simplified, due to the new serializers API.",
+ "title": "Simplification of view logic."
+ },
+ {
+ "location": "/topics/3.0-announcement/#changes-to-prepost-save-hooks",
+ "text": "The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer) . These methods should save the object instance by calling serializer.save() , adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior. For example: def perform_create(self, serializer):\n # Include the owner attribute directly, rather than from request data.\n instance = serializer.save(owner=self.request.user)\n # Perform a custom post-save action.\n send_email(instance.to_email, instance.message) The pre_delete and post_delete hooks no longer exist, and are replaced with .perform_destroy(self, instance) , which should delete the instance and perform any custom actions. def perform_destroy(self, instance):\n # Perform a custom pre-delete action.\n send_deletion_alert(user=instance.created_by, deleted=instance)\n # Delete the object instance.\n instance.delete()",
+ "title": "Changes to pre/post save hooks."
+ },
+ {
+ "location": "/topics/3.0-announcement/#removal-of-view-attributes",
+ "text": "The .object and .object_list 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. I would personally recommend that developers treat view instances as immutable objects in their application code.",
+ "title": "Removal of view attributes."
+ },
+ {
+ "location": "/topics/3.0-announcement/#put-as-create",
+ "text": "Allowing PUT 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 404 responses. Both styles \" PUT as 404\" and \" PUT 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. If you need to restore the previous behavior you may want to include this AllowPUTAsCreateMixin class as a mixin to your views.",
+ "title": "PUT as create."
+ },
+ {
+ "location": "/topics/3.0-announcement/#customizing-error-responses",
+ "text": "The generic views now raise ValidationFailed exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a 400 Bad Request response directly. 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.",
+ "title": "Customizing error responses."
+ },
{
"location": "/topics/3.0-announcement/#the-metadata-api",
"text": "Behavior for dealing with OPTIONS 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. This makes it far easier to use a different style for OPTIONS responses throughout your API, and makes it possible to create third-party metadata policies.",
@@ -2962,14 +4362,49 @@
},
{
"location": "/topics/3.0-announcement/#serializers-as-html-forms",
- "text": "REST framework 3.0 includes templated HTML form rendering for serializers. This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release. Significant changes that you do need to be aware of include: Nested HTML forms are now supported, for example, a UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API. Nested lists of HTML forms are not yet supported, but are planned for 3.1. Because we now use templated HTML form generation, the widget option is no longer available for serializer fields . You can instead control the template that is used for a given field, by using the style dictionary. The style keyword argument for serializer fields. The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with. For example, to use a textarea control instead of the default input control, you would use the following\u2026 additional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n) Similarly, to use a radio button control instead of the default select control, you would use the following\u2026 color_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n) This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.",
+ "text": "REST framework 3.0 includes templated HTML form rendering for serializers. This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release. Significant changes that you do need to be aware of include: Nested HTML forms are now supported, for example, a UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API. Nested lists of HTML forms are not yet supported, but are planned for 3.1. Because we now use templated HTML form generation, the widget option is no longer available for serializer fields . You can instead control the template that is used for a given field, by using the style dictionary.",
"title": "Serializers as HTML forms"
},
+ {
+ "location": "/topics/3.0-announcement/#the-style-keyword-argument-for-serializer-fields",
+ "text": "The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with. For example, to use a textarea control instead of the default input control, you would use the following\u2026 additional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n) Similarly, to use a radio button control instead of the default select control, you would use the following\u2026 color_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n) This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.",
+ "title": "The style keyword argument for serializer fields."
+ },
{
"location": "/topics/3.0-announcement/#api-style",
- "text": "There are some improvements in the default style we use in our API responses. Unicode JSON by default. Unicode JSON is now the default. The UnicodeJSONRenderer class no longer exists, and the UNICODE_JSON setting has been added. To revert this behavior use the new setting: REST_FRAMEWORK = {\n 'UNICODE_JSON': False\n} Compact JSON by default. We now output compact JSON in responses by default. For example, we return: {\"email\":\"amy@example.com\",\"is_admin\":true} Instead of the following: {\"email\": \"amy@example.com\", \"is_admin\": true} The COMPACT_JSON setting has been added, and can be used to revert this behavior if needed: REST_FRAMEWORK = {\n 'COMPACT_JSON': False\n} File fields as URLs The FileField and ImageField classes are now represented as URLs by default. You should ensure you set Django's standard MEDIA_URL setting appropriately, and ensure your application serves the uploaded files . You can revert this behavior, and display filenames in the representation by using the UPLOADED_FILES_USE_URL settings key: REST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n} You can also modify serializer fields individually, using the use_url argument: uploaded_file = serializers.FileField(use_url=False) Also note that you should pass the request 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 https://example.com/url_path/filename.txt . For example: context = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data) If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt . Throttle headers using Retry-After . The custom X-Throttle-Wait-Second header has now been dropped in favor of the standard Retry-After header. You can revert this behavior if needed by writing a custom exception handler for your application. Date and time objects as ISO-8859-1 strings in serializer data. Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date , Time and DateTime objects, and later coerced to strings by the renderer. You can modify this behavior globally by settings the existing DATE_FORMAT , DATETIME_FORMAT and TIME_FORMAT settings keys. Setting these values to None instead of their default value of 'iso-8859-1' will result in native objects being returned in serializer data. REST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n} You can also modify serializer fields individually, using the date_format , time_format and datetime_format arguments: # Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None) Decimals as strings in serializer data. Decimals are now coerced to strings by default in the serializer output. Previously they were returned as Decimal objects, and later coerced to strings by the renderer. You can modify this behavior globally by using the COERCE_DECIMAL_TO_STRING settings key. REST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n} Or modify it on an individual serializer field, using the coerce_to_string keyword argument. # Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n max_digits=10,\n decimal_places=2,\n coerce_to_string=False\n) The default JSON renderer will return float objects for un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.",
+ "text": "There are some improvements in the default style we use in our API responses.",
"title": "API style"
},
+ {
+ "location": "/topics/3.0-announcement/#unicode-json-by-default",
+ "text": "Unicode JSON is now the default. The UnicodeJSONRenderer class no longer exists, and the UNICODE_JSON setting has been added. To revert this behavior use the new setting: REST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}",
+ "title": "Unicode JSON by default."
+ },
+ {
+ "location": "/topics/3.0-announcement/#compact-json-by-default",
+ "text": "We now output compact JSON in responses by default. For example, we return: {\"email\":\"amy@example.com\",\"is_admin\":true} Instead of the following: {\"email\": \"amy@example.com\", \"is_admin\": true} The COMPACT_JSON setting has been added, and can be used to revert this behavior if needed: REST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}",
+ "title": "Compact JSON by default."
+ },
+ {
+ "location": "/topics/3.0-announcement/#file-fields-as-urls",
+ "text": "The FileField and ImageField classes are now represented as URLs by default. You should ensure you set Django's standard MEDIA_URL setting appropriately, and ensure your application serves the uploaded files . You can revert this behavior, and display filenames in the representation by using the UPLOADED_FILES_USE_URL settings key: REST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n} You can also modify serializer fields individually, using the use_url argument: uploaded_file = serializers.FileField(use_url=False) Also note that you should pass the request 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 https://example.com/url_path/filename.txt . For example: context = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data) If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt .",
+ "title": "File fields as URLs"
+ },
+ {
+ "location": "/topics/3.0-announcement/#throttle-headers-using-retry-after",
+ "text": "The custom X-Throttle-Wait-Second header has now been dropped in favor of the standard Retry-After header. You can revert this behavior if needed by writing a custom exception handler for your application.",
+ "title": "Throttle headers using Retry-After."
+ },
+ {
+ "location": "/topics/3.0-announcement/#date-and-time-objects-as-iso-8859-1-strings-in-serializer-data",
+ "text": "Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date , Time and DateTime objects, and later coerced to strings by the renderer. You can modify this behavior globally by settings the existing DATE_FORMAT , DATETIME_FORMAT and TIME_FORMAT settings keys. Setting these values to None instead of their default value of 'iso-8859-1' will result in native objects being returned in serializer data. REST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n} You can also modify serializer fields individually, using the date_format , time_format and datetime_format arguments: # Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)",
+ "title": "Date and time objects as ISO-8859-1 strings in serializer data."
+ },
+ {
+ "location": "/topics/3.0-announcement/#decimals-as-strings-in-serializer-data",
+ "text": "Decimals are now coerced to strings by default in the serializer output. Previously they were returned as Decimal objects, and later coerced to strings by the renderer. You can modify this behavior globally by using the COERCE_DECIMAL_TO_STRING settings key. REST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n} Or modify it on an individual serializer field, using the coerce_to_string keyword argument. # Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n max_digits=10,\n decimal_places=2,\n coerce_to_string=False\n) The default JSON renderer will return float objects for un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.",
+ "title": "Decimals as strings in serializer data."
+ },
{
"location": "/topics/3.0-announcement/#miscellaneous-notes",
"text": "The serializer ChoiceField does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1. 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. Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still create language files with Django if you wish to localize them. APIException subclasses could previously take any arbitrary type in the detail argument. These exceptions now use translatable text strings, and as a result call force_text on the detail argument, which must be a string . If you need complex arguments to an APIException class, you should subclass it and override the __init__() method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.",
@@ -2992,9 +4427,24 @@
},
{
"location": "/topics/3.1-announcement/#pagination",
- "text": "The pagination API has been improved, making it both easier to use, and more powerful. A guide to the headline features follows. For full details, see the pagination documentation . Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes. The PAGINATE_BY settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE settings key should now be used instead. The PAGINATE_BY_PARAM , MAX_PAGINATE_BY settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The paginate_by , page_query_param , paginate_by_param and max_paginate_by generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The pagination_serializer_class view attribute and DEFAULT_PAGINATION_SERIALIZER_CLASS settings key are no longer valid . The pagination API does not use serializers to determine the output format, and you'll need to instead override the get_paginated_response method on a pagination class in order to specify how the output format is controlled. New pagination schemes. Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default. The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject. Pagination controls in the browsable API. Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API: The cursor based pagination renders a more simple style of control: Support for header-based pagination. The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link or Content-Range headers. For more information, see the custom pagination styles documentation.",
+ "text": "The pagination API has been improved, making it both easier to use, and more powerful. A guide to the headline features follows. For full details, see the pagination documentation . Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes. The PAGINATE_BY settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE settings key should now be used instead. The PAGINATE_BY_PARAM , MAX_PAGINATE_BY settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The paginate_by , page_query_param , paginate_by_param and max_paginate_by generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. The pagination_serializer_class view attribute and DEFAULT_PAGINATION_SERIALIZER_CLASS settings key are no longer valid . The pagination API does not use serializers to determine the output format, and you'll need to instead override the get_paginated_response method on a pagination class in order to specify how the output format is controlled.",
"title": "Pagination"
},
+ {
+ "location": "/topics/3.1-announcement/#new-pagination-schemes",
+ "text": "Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default. The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject.",
+ "title": "New pagination schemes."
+ },
+ {
+ "location": "/topics/3.1-announcement/#pagination-controls-in-the-browsable-api",
+ "text": "Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API: The cursor based pagination renders a more simple style of control:",
+ "title": "Pagination controls in the browsable API."
+ },
+ {
+ "location": "/topics/3.1-announcement/#support-for-header-based-pagination",
+ "text": "The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link or Content-Range headers. For more information, see the custom pagination styles documentation.",
+ "title": "Support for header-based pagination."
+ },
{
"location": "/topics/3.1-announcement/#versioning",
"text": "We've made it easier to build versioned APIs . Built-in schemes for versioning include both URL based and Accept header based variations. When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request. For example, when using NamespaceVersioning , and the following hyperlinked serializer: class AccountsSerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = Accounts\n fields = ('account_name', 'users') The output representation would match the version used on the incoming request. Like so: GET http://example.org/v2/accounts/10 # Version 'v2'\n\n{\n \"account_name\": \"europa\",\n \"users\": [\n \"http://example.org/v2/users/12\", # Version 'v2'\n \"http://example.org/v2/users/54\",\n \"http://example.org/v2/users/87\"\n ]\n}",
@@ -3057,9 +4507,19 @@
},
{
"location": "/topics/3.2-announcement/#modifications-to-list-behaviors",
- "text": "There are a couple of bug fixes that are worth calling out as they introduce differing behavior. These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project. ManyToMany fields and blank=True We've now added an allow_empty argument, which can be used with ListSerializer , or with many=True relationships. This is True by default, but can be set to False if you want to disallow empty lists as valid input. As a follow-up to this we are now able to properly mirror the behavior of Django's ModelForm with respect to how many-to-many fields are validated. Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has blank=True set. Here's what the mapping looks like in practice: models.ManyToManyField() \u2192 serializers.PrimaryKeyRelatedField(many=True, allow_empty=False) models.ManyToManyField(blank=True) \u2192 serializers.PrimaryKeyRelatedField(many=True) The upshot is this: If you have many to many fields in your models, then make sure you've included the argument blank=True if you want to allow empty inputs in the equivalent ModelSerializer fields. List fields and allow_null When using allow_null with ListField or a nested many=True serializer the previous behavior was to allow null values as items in the list. The behavior is now to allow null values instead of the list. For example, take the following field: NestedSerializer(many=True, allow_null=True) Previously the validation behavior would be: [{\u2026}, null, {\u2026}] is valid . null is invalid . Our validation behavior as of 3.2.0 is now: [{\u2026}, null, {\u2026}] is invalid . null is valid . If you want to allow null child items, you'll need to instead specify allow_null on the child class, using an explicit ListField instead of many=True . For example: ListField(child=NestedSerializer(allow_null=True))",
+ "text": "There are a couple of bug fixes that are worth calling out as they introduce differing behavior. These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.",
"title": "Modifications to list behaviors"
},
+ {
+ "location": "/topics/3.2-announcement/#manytomany-fields-and-blanktrue",
+ "text": "We've now added an allow_empty argument, which can be used with ListSerializer , or with many=True relationships. This is True by default, but can be set to False if you want to disallow empty lists as valid input. As a follow-up to this we are now able to properly mirror the behavior of Django's ModelForm with respect to how many-to-many fields are validated. Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has blank=True set. Here's what the mapping looks like in practice: models.ManyToManyField() \u2192 serializers.PrimaryKeyRelatedField(many=True, allow_empty=False) models.ManyToManyField(blank=True) \u2192 serializers.PrimaryKeyRelatedField(many=True) The upshot is this: If you have many to many fields in your models, then make sure you've included the argument blank=True if you want to allow empty inputs in the equivalent ModelSerializer fields.",
+ "title": "ManyToMany fields and blank=True"
+ },
+ {
+ "location": "/topics/3.2-announcement/#list-fields-and-allow_null",
+ "text": "When using allow_null with ListField or a nested many=True serializer the previous behavior was to allow null values as items in the list. The behavior is now to allow null values instead of the list. For example, take the following field: NestedSerializer(many=True, allow_null=True) Previously the validation behavior would be: [{\u2026}, null, {\u2026}] is valid . null is invalid . Our validation behavior as of 3.2.0 is now: [{\u2026}, null, {\u2026}] is invalid . null is valid . If you want to allow null child items, you'll need to instead specify allow_null on the child class, using an explicit ListField instead of many=True . For example: ListField(child=NestedSerializer(allow_null=True))",
+ "title": "List fields and allow_null"
+ },
{
"location": "/topics/3.2-announcement/#whats-next",
"text": "The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release. This release is planned to include: Search and filtering controls in the browsable API and admin interface. Improvements and public API for the admin interface. Improvements and public API for our templated HTML forms and fields. Nested object and list support in HTML forms. Thanks once again to all our sponsors and supporters.",
@@ -3107,9 +4567,34 @@
},
{
"location": "/topics/kickstarter-announcement/#sponsors",
- "text": "We've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible. Platinum sponsors Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough. Eventbrite Divio Lulu Potato Wiredrive Cyan Runscope Simple Energy VOKAL Interactive Purple Bit KuwaitNET Gold sponsors Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development. LaterPay Schuberg Philis ProReNata AB SGA Websites Sirono Vinta Software Studio Rapasso Mirus Research Hipo Byte Lightning Kite Opbeat Koordinates Pulsecode Inc. Singing Horse Studio Ltd. Heroku Rheinwerk Verlag Security Compass Django Software Foundation Hipflask Crate Cryptico Corp NextHub Compile WusaWork Envision Linux Silver sponsors The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have choosen to privately support the project at this level. IMT Computer Services Wildfish Thermondo GmbH Providenz alwaysdata.com Triggered Messaging PushPull Technology Ltd Transcode Garfo Shippo Gizmag Tivix Safari Bright Loop ABA Systems beefarm.ru Vzzual.com Infinite Code Crossword Tracker PkgFarm Life. The Game. Blimp Pathwright Fluxility Teonite TrackMaven Phurba Nephila Aditium OpenEye Scientific Software Holvi Cantemo MakeSpace AX Semantics ISL Individual backers : Paul Hallett, Paul Whipp , Dylan Roy, Jannis Leidel, Xavier Ordoquy , Johannes Spielmann , Rob Spectre , Chris Heisel , Marwan Alsabbagh, Haris Ali, Tuomas Toivonen. Advocates The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you! Individual backers : Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel. Corporate backers : Savannah Informatics, Prism Skylabs, Musical Operating Devices. Supporters There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!",
+ "text": "We've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.",
"title": "Sponsors"
},
+ {
+ "location": "/topics/kickstarter-announcement/#platinum-sponsors",
+ "text": "Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough. Eventbrite Divio Lulu Potato Wiredrive Cyan Runscope Simple Energy VOKAL Interactive Purple Bit KuwaitNET",
+ "title": "Platinum sponsors"
+ },
+ {
+ "location": "/topics/kickstarter-announcement/#gold-sponsors",
+ "text": "Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development. LaterPay Schuberg Philis ProReNata AB SGA Websites Sirono Vinta Software Studio Rapasso Mirus Research Hipo Byte Lightning Kite Opbeat Koordinates Pulsecode Inc. Singing Horse Studio Ltd. Heroku Rheinwerk Verlag Security Compass Django Software Foundation Hipflask Crate Cryptico Corp NextHub Compile WusaWork Envision Linux",
+ "title": "Gold sponsors"
+ },
+ {
+ "location": "/topics/kickstarter-announcement/#silver-sponsors",
+ "text": "The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have choosen to privately support the project at this level. IMT Computer Services Wildfish Thermondo GmbH Providenz alwaysdata.com Triggered Messaging PushPull Technology Ltd Transcode Garfo Shippo Gizmag Tivix Safari Bright Loop ABA Systems beefarm.ru Vzzual.com Infinite Code Crossword Tracker PkgFarm Life. The Game. Blimp Pathwright Fluxility Teonite TrackMaven Phurba Nephila Aditium OpenEye Scientific Software Holvi Cantemo MakeSpace AX Semantics ISL Individual backers : Paul Hallett, Paul Whipp , Dylan Roy, Jannis Leidel, Xavier Ordoquy , Johannes Spielmann , Rob Spectre , Chris Heisel , Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.",
+ "title": "Silver sponsors"
+ },
+ {
+ "location": "/topics/kickstarter-announcement/#advocates",
+ "text": "The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you! Individual backers : Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel. Corporate backers : Savannah Informatics, Prism Skylabs, Musical Operating Devices.",
+ "title": "Advocates"
+ },
+ {
+ "location": "/topics/kickstarter-announcement/#supporters",
+ "text": "There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!",
+ "title": "Supporters"
+ },
{
"location": "/topics/mozilla-grant/",
"text": "Mozilla Grant\n\n\nWe have recently been \nawarded a Mozilla grant\n, in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.\n\n\nAdditionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.\n\n\nThe \nCore API\n project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with \nany\n API that exposes a supported schema or hypermedia format.\n\n\nSpecifically, the work includes:\n\n\nClient libraries\n\n\nThis work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.\n\n\n\n\nClient library support in REST framework.\n\n\nSchema \n hypermedia support for REST framework APIs.\n\n\nA test client, allowing you to write tests that emulate a client library interacting with your API.\n\n\nNew tutorial sections on using client libraries to interact with REST framework APIs.\n\n\nPython client library.\n\n\nJavaScript client library.\n\n\nCommand line client.\n\n\n\n\nRealtime APIs\n\n\nThe next goal is to build on the realtime support offered by Django Channels, adding support \n documentation for building realtime API endpoints.\n\n\n\n\nSupport for API subscription endpoints, using REST framework and Django Channels.\n\n\nNew tutorial section on building realtime API endpoints with REST framework.\n\n\nRealtime support in the Python \n Javascript client libraries.\n\n\n\n\nAccountability\n\n\nIn order to ensure that I can be fully focused on trying to secure a sustainable\n\n well-funded open source business I will be leaving my current role at \nDabApps\n\nat the end of May 2016.\n\n\nI have formed a UK limited company, \nEncode\n, which will\nact as the business entity behind REST framework. I will be issuing monthly reports\nfrom Encode on progress both towards the Mozilla grant, and for development time\nfunded via the \nREST framework paid plans\n.\n\n\n\n\n\n\n\n\n #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }\n / Add your own MailChimp form style overrides in your site stylesheet or in this style block.\n We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. /\n\n\n\n\n\n\n \n\n \nStay up to date, with our monthly progress reports...\n\n\n\n \nEmail Address \n\n \n\n\n\n \n\n \n\n \n\n \n \n\n \n\n \n\n \n\n\n\n\n\n\n(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);",
@@ -3197,28 +4682,133 @@
},
{
"location": "/topics/release-notes/#34x-series",
- "text": "3.4 Unreleased Dropped support for EOL Django 1.7 ([#3933][gh3933]) Fixed null foreign keys targeting UUIDField primary keys. ([#3936][gh3936])",
+ "text": "",
"title": "3.4.x series"
},
+ {
+ "location": "/topics/release-notes/#34",
+ "text": "Unreleased Dropped support for EOL Django 1.7 ([#3933][gh3933]) Fixed null foreign keys targeting UUIDField primary keys. ([#3936][gh3936])",
+ "title": "3.4"
+ },
{
"location": "/topics/release-notes/#33x-series",
- "text": "3.3.3 Date : 14th March 2016 . Remove version string from templates. Thanks to @blag for the report and fixes. ( #3878 , #3913 , #3912 ) Fixes vertical html layout for BooleanField . Thanks to Mikalai Radchuk for the fix. ( #3910 ) Silenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. ( #3903 ) Internationalization for authtoken. Thanks to Michael Nacharov for the fix. ( #3887 , #3968 ) Fix Token model as abstract when the authtoken application isn't declared. Thanks to Adam Thomas for the report. ( #3860 , #3858 ) Improve Markdown version compatibility. Thanks to Michael J. Schultz for the fix. ( #3604 , #3842 ) QueryParameterVersioning does not use DEFAULT_VERSION setting. Thanks to Brad Montgomery for the fix. ( #3833 ) Add an explicit on_delete on the models. Thanks to Mads Jensen for the fix. ( #3832 ) Fix DateField.to_representation to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. ( #3819 ) Fixed TimeField not handling string times. Thanks to Areski Belaid for the fix. ( #3809 ) Avoid updates of Meta.extra_kwargs . Thanks to Kevin Massey for the report and fix. ( #3805 , #3804 ) Fix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. ( #3801 ) Document how to avoid CSRF and missing button issues with django-crispy-forms . Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. ( #3787 , #3636 , #3637 ) Improve Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. ( #3786 , #3815 ) Improve authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. ( #3785 ) Fix Min/MaxValueValidator transfer from a model's DecimalField . Thanks to Kevin Brown for the fix. ( #3774 ) Improve HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. ( #3769 ) Fix AutoFilterSet to inherit from default_filter_set . Thanks to Tom Linford for the fix. ( #3753 ) Fix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. ( #3739 ) DateTimeField does not handle empty values correctly. Thanks to Mick Parker for the report and fix. ( #3731 , #3726 ) Raise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. ( #3715 ) Add missing csrf_token in AdminRenderer post form. Thanks to Piotr \u015aniegowski for the fix. ( #3703 ) Refactored _get_reverse_relationships() to use correct to_field . Thanks to Benjamin Phillips for the fix. ( #3696 ) Document the use of get_queryset for RelatedField . Thanks to Ryan Hiebert for the fix. ( #3605 ) Fix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix ( #3962 ) 3.3.2 Date : 14th December 2015 . ListField enforces input is a list. ( #3513 ) Fix regression hiding raw data form. ( #3600 , #3578 ) Fix Python 3.5 compatibility. ( #3534 , #3626 ) Allow setting a custom Django Paginator in pagination.PageNumberPagination . ( #3631 , #3684 ) Fix relational fields without to_fields attribute. ( #3635 , #3634 ) Fix template.render deprecation warnings for Django 1.9. ( #3654 ) Sort response headers in browsable API renderer. ( #3655 ) Use related_objects api for Django 1.9+. ( #3656 , #3252 ) Add confirm modal when deleting. ( #3228 , #3662 ) Reveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. ( #3668 ) Make DRF compatible with multi template engine in Django 1.8. ( #3672 ) Update NestedBoundField to also handle empty string when rendering its form. ( #3677 ) Fix UUID validation to properly catch invalid input types. ( #3687 , #3679 ) Fix caching issues. ( #3628 , #3701 ) Fix Admin and API browser for views without a filter_class. ( #3705 , #3596 , #3597 ) Add app_name to rest_framework.urls. ( #3714 ) Improve authtoken's views to support url versioning. ( #3718 , #3723 ) 3.3.1 Date : 4th November 2015 . Resolve parsing bug when accessing request.POST ( #3592 ) Correctly deal with to_field referring to primary key. ( #3593 ) Allow filter HTML to render when no filter_class is defined. ( #3560 ) Fix admin rendering issues. ( #3564 , #3556 ) Fix issue with DecimalValidator. ( #3568 ) 3.3.0 Date : 28th October 2015 . HTML controls for filters. ( #3315 ) Forms API. ( #3475 ) AJAX browsable API. ( #3410 ) Added JSONField. ( #3454 ) Correctly map to_field when creating ModelSerializer relational fields. ( #3526 ) Include keyword arguments when mapping FilePathField to a serializer field. ( #3536 ) Map appropriate model error_messages on ModelSerializer uniqueness constraints. ( #3435 ) Include max_length constraint for ModelSerializer fields mapped from TextField. ( #3509 ) Added support for Django 1.9. ( #3450 , #3525 ) Removed support for Django 1.5 1.6. ( #3421 , #3429 ) Removed 'south' migrations. ( #3495 )",
+ "text": "",
"title": "3.3.x series"
},
+ {
+ "location": "/topics/release-notes/#333",
+ "text": "Date : 14th March 2016 . Remove version string from templates. Thanks to @blag for the report and fixes. ( #3878 , #3913 , #3912 ) Fixes vertical html layout for BooleanField . Thanks to Mikalai Radchuk for the fix. ( #3910 ) Silenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. ( #3903 ) Internationalization for authtoken. Thanks to Michael Nacharov for the fix. ( #3887 , #3968 ) Fix Token model as abstract when the authtoken application isn't declared. Thanks to Adam Thomas for the report. ( #3860 , #3858 ) Improve Markdown version compatibility. Thanks to Michael J. Schultz for the fix. ( #3604 , #3842 ) QueryParameterVersioning does not use DEFAULT_VERSION setting. Thanks to Brad Montgomery for the fix. ( #3833 ) Add an explicit on_delete on the models. Thanks to Mads Jensen for the fix. ( #3832 ) Fix DateField.to_representation to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. ( #3819 ) Fixed TimeField not handling string times. Thanks to Areski Belaid for the fix. ( #3809 ) Avoid updates of Meta.extra_kwargs . Thanks to Kevin Massey for the report and fix. ( #3805 , #3804 ) Fix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. ( #3801 ) Document how to avoid CSRF and missing button issues with django-crispy-forms . Thanks to Emmanuelle Delescolle, Jos\u00e9 Padilla and Luis San Pablo for the report, analysis and fix. ( #3787 , #3636 , #3637 ) Improve Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. ( #3786 , #3815 ) Improve authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. ( #3785 ) Fix Min/MaxValueValidator transfer from a model's DecimalField . Thanks to Kevin Brown for the fix. ( #3774 ) Improve HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. ( #3769 ) Fix AutoFilterSet to inherit from default_filter_set . Thanks to Tom Linford for the fix. ( #3753 ) Fix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. ( #3739 ) DateTimeField does not handle empty values correctly. Thanks to Mick Parker for the report and fix. ( #3731 , #3726 ) Raise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. ( #3715 ) Add missing csrf_token in AdminRenderer post form. Thanks to Piotr \u015aniegowski for the fix. ( #3703 ) Refactored _get_reverse_relationships() to use correct to_field . Thanks to Benjamin Phillips for the fix. ( #3696 ) Document the use of get_queryset for RelatedField . Thanks to Ryan Hiebert for the fix. ( #3605 ) Fix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix ( #3962 )",
+ "title": "3.3.3"
+ },
+ {
+ "location": "/topics/release-notes/#332",
+ "text": "Date : 14th December 2015 . ListField enforces input is a list. ( #3513 ) Fix regression hiding raw data form. ( #3600 , #3578 ) Fix Python 3.5 compatibility. ( #3534 , #3626 ) Allow setting a custom Django Paginator in pagination.PageNumberPagination . ( #3631 , #3684 ) Fix relational fields without to_fields attribute. ( #3635 , #3634 ) Fix template.render deprecation warnings for Django 1.9. ( #3654 ) Sort response headers in browsable API renderer. ( #3655 ) Use related_objects api for Django 1.9+. ( #3656 , #3252 ) Add confirm modal when deleting. ( #3228 , #3662 ) Reveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. ( #3668 ) Make DRF compatible with multi template engine in Django 1.8. ( #3672 ) Update NestedBoundField to also handle empty string when rendering its form. ( #3677 ) Fix UUID validation to properly catch invalid input types. ( #3687 , #3679 ) Fix caching issues. ( #3628 , #3701 ) Fix Admin and API browser for views without a filter_class. ( #3705 , #3596 , #3597 ) Add app_name to rest_framework.urls. ( #3714 ) Improve authtoken's views to support url versioning. ( #3718 , #3723 )",
+ "title": "3.3.2"
+ },
+ {
+ "location": "/topics/release-notes/#331",
+ "text": "Date : 4th November 2015 . Resolve parsing bug when accessing request.POST ( #3592 ) Correctly deal with to_field referring to primary key. ( #3593 ) Allow filter HTML to render when no filter_class is defined. ( #3560 ) Fix admin rendering issues. ( #3564 , #3556 ) Fix issue with DecimalValidator. ( #3568 )",
+ "title": "3.3.1"
+ },
+ {
+ "location": "/topics/release-notes/#330",
+ "text": "Date : 28th October 2015 . HTML controls for filters. ( #3315 ) Forms API. ( #3475 ) AJAX browsable API. ( #3410 ) Added JSONField. ( #3454 ) Correctly map to_field when creating ModelSerializer relational fields. ( #3526 ) Include keyword arguments when mapping FilePathField to a serializer field. ( #3536 ) Map appropriate model error_messages on ModelSerializer uniqueness constraints. ( #3435 ) Include max_length constraint for ModelSerializer fields mapped from TextField. ( #3509 ) Added support for Django 1.9. ( #3450 , #3525 ) Removed support for Django 1.5 1.6. ( #3421 , #3429 ) Removed 'south' migrations. ( #3495 )",
+ "title": "3.3.0"
+ },
{
"location": "/topics/release-notes/#32x-series",
- "text": "3.2.5 Date : 27th October 2015 . Escape username in optional logout tag. ( #3550 ) 3.2.4 Date : 21th September 2015 . Don't error on missing ViewSet.search_fields attribute. ( #3324 , #3323 ) Fix allow_empty not working on serializers with many=True . ( #3361 , #3364 ) Let DurationField accepts integers. ( #3359 ) Multi-level dictionaries not supported in multipart requests. ( #3314 ) Fix ListField truncation on HTTP PATCH ( #3415 , #2761 ) 3.2.3 Date : 24th August 2015 . Added html_cutoff and html_cutoff_text for limiting select dropdowns. ( #3313 ) Added regex style to SearchFilter . ( #3316 ) Resolve issues with setting blank HTML fields. ( #3318 ) ( #3321 ) Correctly display existing 'select multiple' values in browsable API forms. ( #3290 ) Resolve duplicated validation message for IPAddressField . ([#3249[gh3249]) ( #3250 ) Fix to ensure admin renderer continues to work when pagination is disabled. ( #3275 ) Resolve error with LimitOffsetPagination when count=0, offset=0. ( #3303 ) 3.2.2 Date : 13th August 2015 . Add display_value() method for use when displaying relational field select inputs. ( #3254 ) Fix issue with BooleanField checkboxes incorrectly displaying as checked. ( #3258 ) Ensure empty checkboxes properly set BooleanField to False in all cases. ( #2776 ) Allow WSGIRequest.FILES property without raising incorrect deprecated error. ( #3261 ) Resolve issue with rendering nested serializers in forms. ( #3260 ) Raise an error if user accidentally pass a serializer instance to a response, rather than data. ( #3241 ) 3.2.1 Date : 7th August 2015 . Fix for relational select widgets rendering without any choices. ( #3237 ) Fix for 1 , 0 rendering as true , false in the admin interface. #3227 ) Fix for ListFields with single value in HTML form input. ( #3238 ) Allow request.FILES for compat with Django's HTTPRequest class. ( #3239 ) 3.2.0 Date : 6th August 2015 . Add AdminRenderer . ( #2926 ) Add FilePathField . ( #1854 ) Add allow_empty to ListField . ( #2250 ) Support django-guardian 1.3. ( #3165 ) Support grouped choices. ( #3225 ) Support error forms in browsable API. ( #3024 ) Allow permission classes to customize the error message. ( #2539 ) Support source= method on hyperlinked fields. ( #2690 ) ListField(allow_null=True) now allows null as the list value, not null items in the list. ( #2766 ) ManyToMany() maps to allow_empty=False , ManyToMany(blank=True) maps to allow_empty=True . ( #2804 ) Support custom serialization styles for primary key fields. ( #2789 ) OPTIONS requests support nested representations. ( #2915 ) Set view.action == \"metadata\" for viewsets with OPTIONS requests. ( #3115 ) Support allow_blank on UUIDField . ([#3130][gh#3130]) Do not display view docstrings with 401 or 403 response codes. ( #3216 ) Resolve Django 1.8 deprecation warnings. ( #2886 ) Fix for DecimalField validation. ( #3139 ) Fix behavior of allow_blank=False when used with trim_whitespace=True . ( #2712 ) Fix issue with some field combinations incorrectly mapping to an invalid allow_blank argument. ( #3011 ) Fix for output representations with prefetches and modified querysets. ( #2704 , #2727 ) Fix assertion error when CursorPagination is provided with certains invalid query parameters. (#2920) gh2920 . Fix UnicodeDecodeError when invalid characters included in header with TokenAuthentication . ( #2928 ) Fix transaction rollbacks with @non_atomic_requests decorator. ( #3016 ) Fix duplicate results issue with Oracle databases using SearchFilter . ( #2935 ) Fix checkbox alignment and rendering in browsable API forms. ( #2783 ) Fix for unsaved file objects which should use \"url\": null in the representation. ( #2759 ) Fix field value rendering in browsable API. ( #2416 ) Fix HStoreField to include allow_blank=True in DictField mapping. ( #2659 ) Numerous other cleanups, improvements to error messaging, private API minor fixes.",
+ "text": "",
"title": "3.2.x series"
},
+ {
+ "location": "/topics/release-notes/#325",
+ "text": "Date : 27th October 2015 . Escape username in optional logout tag. ( #3550 )",
+ "title": "3.2.5"
+ },
+ {
+ "location": "/topics/release-notes/#324",
+ "text": "Date : 21th September 2015 . Don't error on missing ViewSet.search_fields attribute. ( #3324 , #3323 ) Fix allow_empty not working on serializers with many=True . ( #3361 , #3364 ) Let DurationField accepts integers. ( #3359 ) Multi-level dictionaries not supported in multipart requests. ( #3314 ) Fix ListField truncation on HTTP PATCH ( #3415 , #2761 )",
+ "title": "3.2.4"
+ },
+ {
+ "location": "/topics/release-notes/#323",
+ "text": "Date : 24th August 2015 . Added html_cutoff and html_cutoff_text for limiting select dropdowns. ( #3313 ) Added regex style to SearchFilter . ( #3316 ) Resolve issues with setting blank HTML fields. ( #3318 ) ( #3321 ) Correctly display existing 'select multiple' values in browsable API forms. ( #3290 ) Resolve duplicated validation message for IPAddressField . ([#3249[gh3249]) ( #3250 ) Fix to ensure admin renderer continues to work when pagination is disabled. ( #3275 ) Resolve error with LimitOffsetPagination when count=0, offset=0. ( #3303 )",
+ "title": "3.2.3"
+ },
+ {
+ "location": "/topics/release-notes/#322",
+ "text": "Date : 13th August 2015 . Add display_value() method for use when displaying relational field select inputs. ( #3254 ) Fix issue with BooleanField checkboxes incorrectly displaying as checked. ( #3258 ) Ensure empty checkboxes properly set BooleanField to False in all cases. ( #2776 ) Allow WSGIRequest.FILES property without raising incorrect deprecated error. ( #3261 ) Resolve issue with rendering nested serializers in forms. ( #3260 ) Raise an error if user accidentally pass a serializer instance to a response, rather than data. ( #3241 )",
+ "title": "3.2.2"
+ },
+ {
+ "location": "/topics/release-notes/#321",
+ "text": "Date : 7th August 2015 . Fix for relational select widgets rendering without any choices. ( #3237 ) Fix for 1 , 0 rendering as true , false in the admin interface. #3227 ) Fix for ListFields with single value in HTML form input. ( #3238 ) Allow request.FILES for compat with Django's HTTPRequest class. ( #3239 )",
+ "title": "3.2.1"
+ },
+ {
+ "location": "/topics/release-notes/#320",
+ "text": "Date : 6th August 2015 . Add AdminRenderer . ( #2926 ) Add FilePathField . ( #1854 ) Add allow_empty to ListField . ( #2250 ) Support django-guardian 1.3. ( #3165 ) Support grouped choices. ( #3225 ) Support error forms in browsable API. ( #3024 ) Allow permission classes to customize the error message. ( #2539 ) Support source= method on hyperlinked fields. ( #2690 ) ListField(allow_null=True) now allows null as the list value, not null items in the list. ( #2766 ) ManyToMany() maps to allow_empty=False , ManyToMany(blank=True) maps to allow_empty=True . ( #2804 ) Support custom serialization styles for primary key fields. ( #2789 ) OPTIONS requests support nested representations. ( #2915 ) Set view.action == \"metadata\" for viewsets with OPTIONS requests. ( #3115 ) Support allow_blank on UUIDField . ([#3130][gh#3130]) Do not display view docstrings with 401 or 403 response codes. ( #3216 ) Resolve Django 1.8 deprecation warnings. ( #2886 ) Fix for DecimalField validation. ( #3139 ) Fix behavior of allow_blank=False when used with trim_whitespace=True . ( #2712 ) Fix issue with some field combinations incorrectly mapping to an invalid allow_blank argument. ( #3011 ) Fix for output representations with prefetches and modified querysets. ( #2704 , #2727 ) Fix assertion error when CursorPagination is provided with certains invalid query parameters. (#2920) gh2920 . Fix UnicodeDecodeError when invalid characters included in header with TokenAuthentication . ( #2928 ) Fix transaction rollbacks with @non_atomic_requests decorator. ( #3016 ) Fix duplicate results issue with Oracle databases using SearchFilter . ( #2935 ) Fix checkbox alignment and rendering in browsable API forms. ( #2783 ) Fix for unsaved file objects which should use \"url\": null in the representation. ( #2759 ) Fix field value rendering in browsable API. ( #2416 ) Fix HStoreField to include allow_blank=True in DictField mapping. ( #2659 ) Numerous other cleanups, improvements to error messaging, private API minor fixes.",
+ "title": "3.2.0"
+ },
{
"location": "/topics/release-notes/#31x-series",
- "text": "3.1.3 Date : 4th June 2015 . Add DurationField . ( #2481 , #2989 ) Add format argument to UUIDField . ( #2788 , #3000 ) MultipleChoiceField empties incorrectly on a partial update using multipart/form-data ( #2993 , #2894 ) Fix a bug in options related to read-only RelatedField . ( #2981 , #2811 ) Fix nested serializers with unique_together relations. ( #2975 ) Allow unexpected values for ChoiceField / MultipleChoiceField representations. ( #2839 , #2940 ) Rollback the transaction on error if ATOMIC_REQUESTS is set. ( #2887 , #2034 ) Set the action on a view when override_method regardless of its None-ness. ( #2933 ) DecimalField accepts 2E+2 as 200 and validates decimal place correctly. ( #2948 , #2947 ) Support basic authentication with custom UserModel that change username . ( #2952 ) IPAddressField improvements. ( #2747 , #2618 , #3008 ) Improve DecimalField for easier subclassing. ( #2695 ) 3.1.2 Date : 13rd May 2015 . DateField.to_representation can handle str and empty values. ( #2656 , #2687 , #2869 ) Use default reason phrases from HTTP standard. ( #2764 , #2763 ) Raise error when ModelSerializer used with abstract model. ( #2757 , #2630 ) Handle reversal of non-API view_name in HyperLinkedRelatedField ( #2724 , #2711 ) Dont require pk strictly for related fields. ( #2745 , #2754 ) Metadata detects null boolean field type. ( #2762 ) Proper handling of depth in nested serializers. ( #2798 ) Display viewset without paginator. ( #2807 ) Don't check for deprecated .model attribute in permissions ( #2818 ) Restrict integer field to integers and strings. ( #2835 , #2836 ) Improve IntegerField to use compiled decimal regex. ( #2853 ) Prevent empty queryset to raise AssertionError. ( #2862 ) DjangoModelPermissions rely on get_queryset . ( #2863 ) Check AcceptHeaderVersioning with content negotiation in place. ( #2868 ) Allow DjangoObjectPermissions to use views that define get_queryset . ( #2905 ) 3.1.1 Date : 23rd March 2015 . Security fix : Escape tab switching cookie name in browsable API. Display input forms in browsable API if serializer_class is used, even when get_serializer method does not exist on the view. ( #2743 ) Use a password input for the AuthTokenSerializer. ( #2741 ) Fix missing anchor closing tag after next button. ( #2691 ) Fix lookup_url_kwarg handling in viewsets. ( #2685 , #2591 ) Fix problem with importing rest_framework.views in apps.py ( #2678 ) LimitOffsetPagination raises TypeError if PAGE_SIZE not set ( #2667 , #2700 ) German translation for min_value field error message references max_value . ( #2645 ) Remove MergeDict . ( #2640 ) Support serializing unsaved models with related fields. ( #2637 , #2641 ) Allow blank/null on radio.html choices. ( #2631 ) 3.1.0 Date : 5th March 2015 . For full details see the 3.1 release announcement .",
+ "text": "",
"title": "3.1.x series"
},
+ {
+ "location": "/topics/release-notes/#313",
+ "text": "Date : 4th June 2015 . Add DurationField . ( #2481 , #2989 ) Add format argument to UUIDField . ( #2788 , #3000 ) MultipleChoiceField empties incorrectly on a partial update using multipart/form-data ( #2993 , #2894 ) Fix a bug in options related to read-only RelatedField . ( #2981 , #2811 ) Fix nested serializers with unique_together relations. ( #2975 ) Allow unexpected values for ChoiceField / MultipleChoiceField representations. ( #2839 , #2940 ) Rollback the transaction on error if ATOMIC_REQUESTS is set. ( #2887 , #2034 ) Set the action on a view when override_method regardless of its None-ness. ( #2933 ) DecimalField accepts 2E+2 as 200 and validates decimal place correctly. ( #2948 , #2947 ) Support basic authentication with custom UserModel that change username . ( #2952 ) IPAddressField improvements. ( #2747 , #2618 , #3008 ) Improve DecimalField for easier subclassing. ( #2695 )",
+ "title": "3.1.3"
+ },
+ {
+ "location": "/topics/release-notes/#312",
+ "text": "Date : 13rd May 2015 . DateField.to_representation can handle str and empty values. ( #2656 , #2687 , #2869 ) Use default reason phrases from HTTP standard. ( #2764 , #2763 ) Raise error when ModelSerializer used with abstract model. ( #2757 , #2630 ) Handle reversal of non-API view_name in HyperLinkedRelatedField ( #2724 , #2711 ) Dont require pk strictly for related fields. ( #2745 , #2754 ) Metadata detects null boolean field type. ( #2762 ) Proper handling of depth in nested serializers. ( #2798 ) Display viewset without paginator. ( #2807 ) Don't check for deprecated .model attribute in permissions ( #2818 ) Restrict integer field to integers and strings. ( #2835 , #2836 ) Improve IntegerField to use compiled decimal regex. ( #2853 ) Prevent empty queryset to raise AssertionError. ( #2862 ) DjangoModelPermissions rely on get_queryset . ( #2863 ) Check AcceptHeaderVersioning with content negotiation in place. ( #2868 ) Allow DjangoObjectPermissions to use views that define get_queryset . ( #2905 )",
+ "title": "3.1.2"
+ },
+ {
+ "location": "/topics/release-notes/#311",
+ "text": "Date : 23rd March 2015 . Security fix : Escape tab switching cookie name in browsable API. Display input forms in browsable API if serializer_class is used, even when get_serializer method does not exist on the view. ( #2743 ) Use a password input for the AuthTokenSerializer. ( #2741 ) Fix missing anchor closing tag after next button. ( #2691 ) Fix lookup_url_kwarg handling in viewsets. ( #2685 , #2591 ) Fix problem with importing rest_framework.views in apps.py ( #2678 ) LimitOffsetPagination raises TypeError if PAGE_SIZE not set ( #2667 , #2700 ) German translation for min_value field error message references max_value . ( #2645 ) Remove MergeDict . ( #2640 ) Support serializing unsaved models with related fields. ( #2637 , #2641 ) Allow blank/null on radio.html choices. ( #2631 )",
+ "title": "3.1.1"
+ },
+ {
+ "location": "/topics/release-notes/#310",
+ "text": "Date : 5th March 2015 . For full details see the 3.1 release announcement .",
+ "title": "3.1.0"
+ },
{
"location": "/topics/release-notes/#30x-series",
- "text": "3.0.5 Date : 10th February 2015 . Fix a bug where _closable_objects breaks pickling. ( #1850 , #2492 ) Allow non-standard User models with Throttling . ( #2524 ) Support custom User.db_table in TokenAuthentication migration. ( #2479 ) Fix misleading AttributeError tracebacks on Request objects. ( #2530 , #2108 ) ManyRelatedField.get_value clearing field on partial update. ( #2475 ) Removed '.model' shortcut from code. ( #2486 ) Fix detail_route and list_route mutable argument. ( #2518 ) Prefetching the user object when getting the token in TokenAuthentication . ( #2519 ) 3.0.4 Date : 28th January 2015 . Django 1.8a1 support. ( #2425 , #2446 , #2441 ) Add DictField and support Django 1.8 HStoreField . ( #2451 , #2106 ) Add UUIDField and support Django 1.8 UUIDField . ( #2448 , #2433 , #2432 ) BaseRenderer.render now raises NotImplementedError . ( #2434 ) Fix timedelta JSON serialization on Python 2.6. ( #2430 ) ResultDict and ResultList now appear as standard dict/list. ( #2421 ) Fix visible HiddenField in the HTML form of the web browsable API page. ( #2410 ) Use OrderedDict for RelatedField.choices . ( #2408 ) Fix ident format when using HTTP_X_FORWARDED_FOR . ( #2401 ) Fix invalid key with memcached while using throttling. ( #2400 ) Fix FileUploadParser with version 3.x. ( #2399 ) Fix the serializer inheritance. ( #2388 ) Fix caching issues with ReturnDict . ( #2360 ) 3.0.3 Date : 8th January 2015 . Fix MinValueValidator on models.DateField . ( #2369 ) Fix serializer missing context when pagination is used. ( #2355 ) Namespaced router URLs are now supported by the DefaultRouter . ( #2351 ) required=False allows omission of value for output. ( #2342 ) Use textarea input for models.TextField . ( #2340 ) Use custom ListSerializer for pagination if required. ( #2331 , #2327 ) Better behavior with null and '' for blank HTML fields. ( #2330 ) Ensure fields in exclude are model fields. ( #2319 ) Fix IntegerField and max_length argument incompatibility. ( #2317 ) Fix the YAML encoder for 3.0 serializers. ( #2315 , #2283 ) Fix the behavior of empty HTML fields. ( #2311 , #1101 ) Fix Metaclass attribute depth ignoring fields attribute. ( #2287 ) Fix format_suffix_patterns to work with Django's i18n_patterns . ( #2278 ) Ability to customize router URLs for custom actions, using url_path . ( #2010 ) Don't install Django REST Framework as egg. ( #2386 ) 3.0.2 Date : 17th December 2014 . Ensure request.user is made available to response middleware. ( #2155 ) Client.logout() also cancels any existing force_authenticate . ( #2218 , #2259 ) Extra assertions and better checks to preventing incorrect serializer API use. ( #2228 , #2234 , #2262 , #2263 , #2266 , #2267 , #2289 , #2291 ) Fixed min_length message for CharField . ( #2255 ) Fix UnicodeDecodeError , which can occur on serializer repr . ( #2270 , #2279 ) Fix empty HTML values when a default is provided. ( #2280 , #2294 ) Fix SlugRelatedField raising UnicodeEncodeError when used as a multiple choice input. ( #2290 ) 3.0.1 Date : 11th December 2014 . More helpful error message when the default Serializer create() fails. ( #2013 ) Raise error when attempting to save serializer if data is not valid. ( #2098 ) Fix FileUploadParser breaks with empty file names and multiple upload handlers. ( #2109 ) Improve BindingDict to support standard dict-functions. ( #2135 , #2163 ) Add validate() to ListSerializer . ( #2168 , #2225 , #2232 ) Fix JSONP renderer failing to escape some characters. ( #2169 , #2195 ) Add missing default style for FileField . ( #2172 ) Actions are required when calling ViewSet.as_view() . ( #2175 ) Add allow_blank to ChoiceField . ( #2184 , #2239 ) Cosmetic fixes in the HTML renderer. ( #2187 ) Raise error if fields on serializer is not a list of strings. ( #2193 , #2213 ) Improve checks for nested creates and updates. ( #2194 , #2196 ) validated_attrs argument renamed to validated_data in Serializer create() / update() . ( #2197 ) Remove deprecated code to reflect the dropped Django versions. ( #2200 ) Better serializer errors for nested writes. ( #2202 , #2215 ) Fix pagination and custom permissions incompatibility. ( #2205 ) Raise error if fields on serializer is not a list of strings. ( #2213 ) Add missing translation markers for relational fields. ( #2231 ) Improve field lookup behavior for dicts/mappings. ( #2244 , #2243 ) Optimized hyperlinked PK. ( #2242 ) 3.0.0 Date : 1st December 2014 For full details see the 3.0 release announcement . For older release notes, please see the version 2.x documentation .",
+ "text": "",
"title": "3.0.x series"
+ },
+ {
+ "location": "/topics/release-notes/#305",
+ "text": "Date : 10th February 2015 . Fix a bug where _closable_objects breaks pickling. ( #1850 , #2492 ) Allow non-standard User models with Throttling . ( #2524 ) Support custom User.db_table in TokenAuthentication migration. ( #2479 ) Fix misleading AttributeError tracebacks on Request objects. ( #2530 , #2108 ) ManyRelatedField.get_value clearing field on partial update. ( #2475 ) Removed '.model' shortcut from code. ( #2486 ) Fix detail_route and list_route mutable argument. ( #2518 ) Prefetching the user object when getting the token in TokenAuthentication . ( #2519 )",
+ "title": "3.0.5"
+ },
+ {
+ "location": "/topics/release-notes/#304",
+ "text": "Date : 28th January 2015 . Django 1.8a1 support. ( #2425 , #2446 , #2441 ) Add DictField and support Django 1.8 HStoreField . ( #2451 , #2106 ) Add UUIDField and support Django 1.8 UUIDField . ( #2448 , #2433 , #2432 ) BaseRenderer.render now raises NotImplementedError . ( #2434 ) Fix timedelta JSON serialization on Python 2.6. ( #2430 ) ResultDict and ResultList now appear as standard dict/list. ( #2421 ) Fix visible HiddenField in the HTML form of the web browsable API page. ( #2410 ) Use OrderedDict for RelatedField.choices . ( #2408 ) Fix ident format when using HTTP_X_FORWARDED_FOR . ( #2401 ) Fix invalid key with memcached while using throttling. ( #2400 ) Fix FileUploadParser with version 3.x. ( #2399 ) Fix the serializer inheritance. ( #2388 ) Fix caching issues with ReturnDict . ( #2360 )",
+ "title": "3.0.4"
+ },
+ {
+ "location": "/topics/release-notes/#303",
+ "text": "Date : 8th January 2015 . Fix MinValueValidator on models.DateField . ( #2369 ) Fix serializer missing context when pagination is used. ( #2355 ) Namespaced router URLs are now supported by the DefaultRouter . ( #2351 ) required=False allows omission of value for output. ( #2342 ) Use textarea input for models.TextField . ( #2340 ) Use custom ListSerializer for pagination if required. ( #2331 , #2327 ) Better behavior with null and '' for blank HTML fields. ( #2330 ) Ensure fields in exclude are model fields. ( #2319 ) Fix IntegerField and max_length argument incompatibility. ( #2317 ) Fix the YAML encoder for 3.0 serializers. ( #2315 , #2283 ) Fix the behavior of empty HTML fields. ( #2311 , #1101 ) Fix Metaclass attribute depth ignoring fields attribute. ( #2287 ) Fix format_suffix_patterns to work with Django's i18n_patterns . ( #2278 ) Ability to customize router URLs for custom actions, using url_path . ( #2010 ) Don't install Django REST Framework as egg. ( #2386 )",
+ "title": "3.0.3"
+ },
+ {
+ "location": "/topics/release-notes/#302",
+ "text": "Date : 17th December 2014 . Ensure request.user is made available to response middleware. ( #2155 ) Client.logout() also cancels any existing force_authenticate . ( #2218 , #2259 ) Extra assertions and better checks to preventing incorrect serializer API use. ( #2228 , #2234 , #2262 , #2263 , #2266 , #2267 , #2289 , #2291 ) Fixed min_length message for CharField . ( #2255 ) Fix UnicodeDecodeError , which can occur on serializer repr . ( #2270 , #2279 ) Fix empty HTML values when a default is provided. ( #2280 , #2294 ) Fix SlugRelatedField raising UnicodeEncodeError when used as a multiple choice input. ( #2290 )",
+ "title": "3.0.2"
+ },
+ {
+ "location": "/topics/release-notes/#301",
+ "text": "Date : 11th December 2014 . More helpful error message when the default Serializer create() fails. ( #2013 ) Raise error when attempting to save serializer if data is not valid. ( #2098 ) Fix FileUploadParser breaks with empty file names and multiple upload handlers. ( #2109 ) Improve BindingDict to support standard dict-functions. ( #2135 , #2163 ) Add validate() to ListSerializer . ( #2168 , #2225 , #2232 ) Fix JSONP renderer failing to escape some characters. ( #2169 , #2195 ) Add missing default style for FileField . ( #2172 ) Actions are required when calling ViewSet.as_view() . ( #2175 ) Add allow_blank to ChoiceField . ( #2184 , #2239 ) Cosmetic fixes in the HTML renderer. ( #2187 ) Raise error if fields on serializer is not a list of strings. ( #2193 , #2213 ) Improve checks for nested creates and updates. ( #2194 , #2196 ) validated_attrs argument renamed to validated_data in Serializer create() / update() . ( #2197 ) Remove deprecated code to reflect the dropped Django versions. ( #2200 ) Better serializer errors for nested writes. ( #2202 , #2215 ) Fix pagination and custom permissions incompatibility. ( #2205 ) Raise error if fields on serializer is not a list of strings. ( #2213 ) Add missing translation markers for relational fields. ( #2231 ) Improve field lookup behavior for dicts/mappings. ( #2244 , #2243 ) Optimized hyperlinked PK. ( #2242 )",
+ "title": "3.0.1"
+ },
+ {
+ "location": "/topics/release-notes/#300",
+ "text": "Date : 1st December 2014 For full details see the 3.0 release announcement . For older release notes, please see the version 2.x documentation .",
+ "title": "3.0.0"
}
]
}
\ No newline at end of file
diff --git a/nav.html b/nav.html
new file mode 100644
index 000000000..7fb42ee8e
--- /dev/null
+++ b/nav.html
@@ -0,0 +1,46 @@
+
diff --git a/sitemap.xml b/sitemap.xml
index ffd8a3ec1..9bb2ca3ce 100644
--- a/sitemap.xml
+++ b/sitemap.xml
@@ -4,7 +4,7 @@
http://www.django-rest-framework.org//
- 2016-05-28
+ 2016-06-24
daily
@@ -13,43 +13,43 @@
http://www.django-rest-framework.org//tutorial/quickstart/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//tutorial/1-serialization/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//tutorial/2-requests-and-responses/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//tutorial/3-class-based-views/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//tutorial/4-authentication-and-permissions/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//tutorial/5-relationships-and-hyperlinked-apis/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//tutorial/6-viewsets-and-routers/
- 2016-05-28
+ 2016-06-24
daily
@@ -59,157 +59,157 @@
http://www.django-rest-framework.org//api-guide/requests/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/responses/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/views/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/generic-views/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/viewsets/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/routers/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/parsers/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/renderers/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/serializers/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/fields/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/relations/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/validators/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/authentication/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/permissions/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/throttling/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/filtering/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/pagination/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/versioning/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/content-negotiation/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/metadata/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/format-suffixes/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/reverse/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/exceptions/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/status-codes/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/testing/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//api-guide/settings/
- 2016-05-28
+ 2016-06-24
daily
@@ -219,109 +219,109 @@
http://www.django-rest-framework.org//topics/documenting-your-api/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/internationalization/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/ajax-csrf-cors/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/html-and-forms/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/browser-enhancements/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/browsable-api/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/rest-hypermedia-hateoas/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/third-party-resources/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/contributing/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/project-management/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/3.0-announcement/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/3.1-announcement/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/3.2-announcement/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/3.3-announcement/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/kickstarter-announcement/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/mozilla-grant/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/funding/
- 2016-05-28
+ 2016-06-24
daily
http://www.django-rest-framework.org//topics/release-notes/
- 2016-05-28
+ 2016-06-24
daily
diff --git a/topics/3.0-announcement/index.html b/topics/3.0-announcement/index.html
index 06f900e5e..fa84132e1 100644
--- a/topics/3.0-announcement/index.html
+++ b/topics/3.0-announcement/index.html
@@ -434,7 +434,7 @@
Below is an in-depth guide to the API changes and migration notes for 3.0.
-
+
The usage of request.DATA
and request.FILES
is now pending deprecation in favor of a single request.data
attribute that contains all the parsed data.
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.
You may now pass all the request data to a serializer class in a single argument:
@@ -466,7 +466,7 @@ ExampleSerializer(data=request.DATA, files=request.FILES)
Calling serializer.save()
then saves and returns the new object instance.
The resulting API changes are further detailed below.
-
+
The .restore_object()
method is now removed, and we instead have two separate methods, .create()
and .update()
. These methods work slightly different to the previous .restore_object()
.
When using the .create()
and .update()
methods you should both create and save the object instance. This is in contrast to the previous .restore_object()
behavior that would instantiate the object but not save it.
These methods also replace the optional .save_object()
method, which no longer exists.
@@ -498,7 +498,7 @@ def create(self, validated_data):
return Snippet.objects.create(**validated_data)
Note that these methods should return the newly created object instance.
-
+
You must now use the .validated_data
attribute if you need to inspect the data before saving, rather than using the .object
attribute, which no longer exists.
For example the following code is no longer valid:
if serializer.is_valid():
@@ -846,7 +846,7 @@ def all_high_scores(request):
-
+
There are some minor tweaks to the field base classes.
Previously we had these two base classes:
@@ -858,7 +858,7 @@ def all_high_scores(request):
Field
is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.
ReadOnlyField
is a concrete implementation for read-only fields that simply returns the attribute value without modification.
-
+
REST framework now has more explicit and clear control over validating empty values for fields.
Previously the meaning of the required=False
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 None
or the empty string.
We now have a better separation, with separate required
, allow_null
and allow_blank
arguments.
@@ -968,7 +968,7 @@ This removes some magic and makes it easier and more obvious to move between imp
The following usage will now raise an error:
email = serializers.EmailField(source='email')
-
+
REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit Serializer
class instead of using ModelSerializer
.
The UniqueValidator
should be applied to a serializer field, and takes a single queryset
argument.
from rest_framework import serializers
diff --git a/topics/ajax-csrf-cors/index.html b/topics/ajax-csrf-cors/index.html
index 4f5a74fea..2963f02de 100644
--- a/topics/ajax-csrf-cors/index.html
+++ b/topics/ajax-csrf-cors/index.html
@@ -346,7 +346,7 @@
- Working with AJAX, CSRF CORS
+ Working with AJAX, CSRF & CORS
diff --git a/topics/contributing/index.html b/topics/contributing/index.html
index 8557029f6..2cae2a608 100644
--- a/topics/contributing/index.html
+++ b/topics/contributing/index.html
@@ -492,7 +492,7 @@ pip install -r requirements.txt
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
-You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox
globally, and then simply run:
+You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox
globally, and then simply run:
tox
diff --git a/topics/html-and-forms/index.html b/topics/html-and-forms/index.html
index b8d2dc2e6..f8c45e9ed 100644
--- a/topics/html-and-forms/index.html
+++ b/topics/html-and-forms/index.html
@@ -346,7 +346,7 @@
- HTML Forms
+ HTML & Forms
@@ -565,22 +565,22 @@ class ProfileDetail(APIView):
select.html |
-ChoiceField or relational field types |
+ChoiceField or relational field types |
hide_label |
radio.html |
-ChoiceField or relational field types |
+ChoiceField or relational field types |
inline, hide_label |
select_multiple.html |
-MultipleChoiceField or relational fields with many=True |
+MultipleChoiceField or relational fields with many=True |
hide_label |
checkbox_multiple.html |
-MultipleChoiceField or relational fields with many=True |
+MultipleChoiceField or relational fields with many=True |
inline, hide_label |
@@ -595,7 +595,7 @@ class ProfileDetail(APIView):
list_fieldset.html |
-ListField or nested serializer with many=True |
+ListField or nested serializer with many=True |
hide_label |
diff --git a/topics/mozilla-grant/index.html b/topics/mozilla-grant/index.html
index fa24deb35..96e59087e 100644
--- a/topics/mozilla-grant/index.html
+++ b/topics/mozilla-grant/index.html
@@ -380,7 +380,7 @@
We have recently been awarded a Mozilla grant, in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.
Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.
-The Core API project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with any API that exposes a supported schema or hypermedia format.
+The Core API project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with any API that exposes a supported schema or hypermedia format.
Specifically, the work includes:
This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.
diff --git a/topics/rest-hypermedia-hateoas/index.html b/topics/rest-hypermedia-hateoas/index.html
index 139bf0823..57a052ea5 100644
--- a/topics/rest-hypermedia-hateoas/index.html
+++ b/topics/rest-hypermedia-hateoas/index.html
@@ -346,7 +346,7 @@
- REST, Hypermedia HATEOAS
+ REST, Hypermedia & HATEOAS
diff --git a/topics/third-party-resources/index.html b/topics/third-party-resources/index.html
index d5f3b36ba..30a5472f4 100644
--- a/topics/third-party-resources/index.html
+++ b/topics/third-party-resources/index.html
@@ -470,7 +470,7 @@ You probably want to also tag the version now:
Shorter form to run the tests for a given test method.
$ ./runtests.py test_this_method
-To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using tox
. Tox is a generic virtualenv management and test command line tool.
+To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using tox
. Tox is a generic virtualenv management and test command line tool.
First, install tox
globally.
$ pip install tox
@@ -528,7 +528,7 @@ You probably want to also tag the version now:
- drf-compound-fields - Provides "compound" serializer fields, such as lists of simple values.
- django-extra-fields - Provides extra serializer fields.
-- django-versatileimagefield - Provides a drop-in replacement for Django's stock
ImageField
that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.
+- django-versatileimagefield - Provides a drop-in replacement for Django's stock
ImageField
that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.
@@ -585,6 +585,7 @@ You probably want to also tag the version now:
ViewSets and Routers - django-rest-framework part 3
Django Rest Framework User Endpoint
Check credentials using Django Rest Framework
+Django REST Framework course
diff --git a/tutorial/2-requests-and-responses/index.html b/tutorial/2-requests-and-responses/index.html
index 312ec0003..4d4372d54 100644
--- a/tutorial/2-requests-and-responses/index.html
+++ b/tutorial/2-requests-and-responses/index.html
@@ -555,6 +555,7 @@ http --json POST http://127.0.0.1:8000/snippets/ code="print 456"
"style": "friendly"
}
+If you add a --debug
switch to the http
requests above, you will be able to see the request type in request headers.
Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.
Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
diff --git a/tutorial/4-authentication-and-permissions/index.html b/tutorial/4-authentication-and-permissions/index.html
index e4fbab679..4f5a644d3 100644
--- a/tutorial/4-authentication-and-permissions/index.html
+++ b/tutorial/4-authentication-and-permissions/index.html
@@ -346,7 +346,7 @@
-
- Tutorial 4: Authentication Permissions
+ Tutorial 4: Authentication & Permissions
diff --git a/tutorial/5-relationships-and-hyperlinked-apis/index.html b/tutorial/5-relationships-and-hyperlinked-apis/index.html
index b7b91e560..ee17f4527 100644
--- a/tutorial/5-relationships-and-hyperlinked-apis/index.html
+++ b/tutorial/5-relationships-and-hyperlinked-apis/index.html
@@ -346,7 +346,7 @@
-
- Tutorial 5: Relationships Hyperlinked APIs
+ Tutorial 5: Relationships & Hyperlinked APIs
diff --git a/tutorial/6-viewsets-and-routers/index.html b/tutorial/6-viewsets-and-routers/index.html
index 9121479b7..aef6c9408 100644
--- a/tutorial/6-viewsets-and-routers/index.html
+++ b/tutorial/6-viewsets-and-routers/index.html
@@ -346,7 +346,7 @@
-
- Tutorial 6: ViewSets Routers
+ Tutorial 6: ViewSets & Routers
diff --git a/tutorial/quickstart/index.html b/tutorial/quickstart/index.html
index 9e9fc9ea8..64dd98d7d 100644
--- a/tutorial/quickstart/index.html
+++ b/tutorial/quickstart/index.html
@@ -496,7 +496,7 @@ REST_FRAMEWORK = {
We're now ready to test the API we've built. Let's fire up the server from the command line.
-
python ./manage.py runserver
+python manage.py runserver
We can now access our API, both from the command-line, using tools like curl
...
bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
@@ -545,7 +545,7 @@ HTTP/1.1 200 OK
]
}
-Or directly through the browser...
+Or directly through the browser, by going to the URL http://127.0.0.1:8000/users/
...
If you're working through the browser, make sure to login using the control in the top right corner.
Great, that was easy!