diff --git a/api-guide/caching/index.html b/api-guide/caching/index.html index d8ef1ce85..df1522e60 100644 --- a/api-guide/caching/index.html +++ b/api-guide/caching/index.html @@ -436,7 +436,7 @@ provided in Django.
Django provides a method_decorator
to use
decorators with class based views. This can be used with
-with other cache decorators such as cache_page
and
+other cache decorators such as cache_page
and
vary_on_cookie
.
from rest_framework.response import Response
from rest_framework.views import APIView
diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html
index c7f75e117..e4857b6d8 100644
--- a/api-guide/fields/index.html
+++ b/api-guide/fields/index.html
@@ -707,7 +707,14 @@ color_channel = serializers.ChoiceField(
BooleanField
A boolean representation.
When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to False
, even if it has a default=True
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.
-Note that default BooleanField
instances will be generated with a required=False
option (since Django models.BooleanField
is always blank=True
). If you want to change this behaviour explicitly declare the BooleanField
on the serializer class.
+Note that Django 2.1 removed the blank
kwarg from models.BooleanField
.
+Prior to Django 2.1 models.BooleanField
fields were always blank=True
. Thus
+since Django 2.1 default serializers.BooleanField
instances will be generated
+without the required
kwarg (i.e. equivalent to required=True
) whereas with
+previous versions of Django, default BooleanField
instances will be generated
+with a required=False
option. If you want to control this behaviour manually,
+explicitly declare the BooleanField
on the serializer class, or use the
+extra_kwargs
option to set the required
flag.
Corresponds to django.db.models.fields.BooleanField
.
Signature: BooleanField()
NullBooleanField
diff --git a/api-guide/filtering/index.html b/api-guide/filtering/index.html
index 410ef2665..971dcb6a7 100644
--- a/api-guide/filtering/index.html
+++ b/api-guide/filtering/index.html
@@ -616,7 +616,7 @@ class UserListView(generics.ListAPIView):
"""
model = Product
serializer_class = ProductSerializer
- filter_class = ProductFilter
+ filterset_class = ProductFilter
def get_queryset(self):
user = self.request.user
@@ -642,12 +642,12 @@ class UserListView(generics.ListAPIView):
...
filter_backends = (DjangoFilterBackend,)
-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.
If all you need is simple equality-based filtering, you can set a filterset_fields
attribute on the view, or viewset, listing the set of fields you wish to filter against.
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = (DjangoFilterBackend,)
- filter_fields = ('category', 'in_stock')
+ filterset_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
@@ -686,6 +686,12 @@ class UserListView(generics.ListAPIView):
search_fields = ('=username', '=email')
By default, the search parameter is named 'search
', but this may be overridden with the SEARCH_PARAM
setting.
+To dynamically change search fields based on request content, it's possible to subclass the SearchFilter
and override the get_search_fields()
function. For example, the following subclass will only search on title
if the query parameter title_only
is in the request:
+class CustomSearchFilter(self, view, request):
+ if request.query_params.get('title_only'):
+ return ('title',)
+ return super(CustomSearchFilter, self).get_search_fields(view, request)
+
For more details, see the Django documentation.
OrderingFilter
diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html
index 710f97059..c7aabe589 100644
--- a/api-guide/pagination/index.html
+++ b/api-guide/pagination/index.html
@@ -726,7 +726,7 @@ that REST framework provides, by implementing a get_schema_fields()
drf-proxy-pagination
The drf-proxy-pagination
package includes a ProxyPagination
class which allows to choose pagination class with a query parameter.
link-header-pagination
-The django-rest-framework-link-header-pagination
package includes a LinkHeaderPagination
class which provides pagination via an HTTP Link
header as desribed in Github's developer documentation.
+The django-rest-framework-link-header-pagination
package includes a LinkHeaderPagination
class which provides pagination via an HTTP Link
header as described in Github's developer documentation.
diff --git a/api-guide/permissions/index.html b/api-guide/permissions/index.html
index 79c3dbae0..99913c616 100644
--- a/api-guide/permissions/index.html
+++ b/api-guide/permissions/index.html
@@ -484,7 +484,7 @@
- Django Rest Framework API Key
+ Django REST Framework API Key
@@ -519,8 +519,8 @@
Together with authentication and throttling, permissions determine whether a request should be granted or denied access.
Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user
and request.auth
properties to determine if the incoming request should be permitted.
-Permissions are used to grant or deny access different classes of users to different parts of the API.
-The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds the IsAuthenticated
class in REST framework.
+Permissions are used to grant or deny access for different classes of users to different parts of the API.
+The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated
class in REST framework.
A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the IsAuthenticatedOrReadOnly
class in REST framework.
How permissions are determined
Permissions in REST framework are always defined as a list of permission classes.
@@ -545,6 +545,15 @@ or if you override the get_object
method on a generic view, then yo
self.check_object_permissions(self.request, obj)
return obj
+Note: With the exception of DjangoObjectPermissions
, the provided
+permission classes in rest_framework.permssions
do not implement the
+methods necessary to check object permissions.
If you wish to use the provided permission classes in order to check object
+permissions, you must subclass them and implement the
+has_object_permission()
method described in the Custom
+permissions section (below).
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.
@@ -608,7 +617,7 @@ class ExampleView(APIView): } return Response(content) -Note: it only supports & -and- and | -or-.
+Note: it supports & (and), | (or) and ~ (not).
The DRY Rest Permissions package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.
The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users.
-The Django Rest Framework API Key package allows you to ensure that every request made to the server requires an API key header. You can generate one from the django admin interface.
+The Django REST Framework API Key package provides the ability to authorize clients based on customizable API key headers. This package is targeted at situations in which regular user-based authentication (e.g. TokenAuthentication
) is not suitable, e.g. allowing non-human clients to safely use your API. API keys are generated and validated through cryptographic methods and can be created and revoked from the Django admin interface at anytime.
The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.
diff --git a/api-guide/relations/index.html b/api-guide/relations/index.html index a4d6ce2d0..df3314346 100644 --- a/api-guide/relations/index.html +++ b/api-guide/relations/index.html @@ -570,11 +570,11 @@ class Track(models.Model): unique_together = ('album', 'order') ordering = ['order'] - def __unicode__(self): + def __str__(self): return '%d: %s' % (self.order, self.title)StringRelatedField
may be used to represent the target of the relationship using its __unicode__
method.
StringRelatedField
may be used to represent the target of the relationship using its __str__
method.
For example, the following serializer.
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)
@@ -945,7 +945,7 @@ class CustomerHyperlink(serializers.HyperlinkedRelatedField):
object_id = models.PositiveIntegerField()
tagged_object = GenericForeignKey('content_type', 'object_id')
- def __unicode__(self):
+ def __str__(self):
return self.tag_name
And the following two models, which may have associated tags:
diff --git a/api-guide/requests/index.html b/api-guide/requests/index.html index 22012376c..e128c6d41 100644 --- a/api-guide/requests/index.html +++ b/api-guide/requests/index.html @@ -530,7 +530,7 @@The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types.
The renderer instance what was selected by the content negotiation stage.
+The renderer instance that was selected by the content negotiation stage.
A string representing the media type that was accepted by the content negotiation stage.
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.
@@ -838,7 +838,7 @@ class GameRecord(serializers.Serializer):By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the partial
argument in order to allow partial updates.
# Update `comment` with partial data
-serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)
+serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)
The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.
@@ -871,7 +871,7 @@ class CommentSerializer(serializers.Serializer): serializer.is_valid() # False serializer.errors -# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']} +# {'user': {'email': ['Enter a valid e-mail address.']}, 'created': ['This field is required.']}Similarly, the .validated_data
property will include nested data structures.
.create()
methods for nested representationsYou can provide arbitrary additional context by passing a context
argument when instantiating the serializer. For example:
serializer = AccountSerializer(account, context={'request': request})
serializer.data
-# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
+# {'id': 6, 'owner': '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.
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate cache settings. The default value of LocMemCache
backend should be okay for simple setups. See Django's cache documentation for more details.
If you need to use a cache other than 'default'
, you can do so by creating a custom throttle class and setting the cache
attribute. For example:
class CustomAnonRateThrottle(AnonRateThrottle):
- cache = get_cache('alternate')
+from django.core.cache import caches
+
+class CustomAnonRateThrottle(AnonRateThrottle):
+ cache = caches['alternate']
You'll need to remember to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES'
settings key, or using the throttle_classes
view attribute.
diff --git a/community/3.0-announcement/index.html b/community/3.0-announcement/index.html
index 4c55848ea..91e17b1e2 100644
--- a/community/3.0-announcement/index.html
+++ b/community/3.0-announcement/index.html
@@ -763,7 +763,7 @@ LocationRatingSerializer():
These fields will be mapped to serializers.ReadOnlyField()
instances.
>>> serializer = InvitationSerializer()
->>> print repr(serializer)
+>>> print(repr(serializer))
InvitationSerializer():
to_email = EmailField(max_length=75)
message = CharField(max_length=1000)
diff --git a/community/release-notes/index.html b/community/release-notes/index.html
index e38de04fd..e3ddd77c2 100644
--- a/community/release-notes/index.html
+++ b/community/release-notes/index.html
@@ -486,10 +486,10 @@
The timeline for deprecation of a feature present in version 1.0 would work as follows:
-
-
Version 1.1 would remain fully backwards compatible with 1.0, but would raise PendingDeprecationWarning
warnings if you use the feature that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test
, you'll be warned of any API changes you need to make.
+Version 1.1 would remain fully backwards compatible with 1.0, but would raise RemovedInDRF13Warning
warnings, subclassing PendingDeprecationWarning
, if you use the feature that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using python -Wd manage.py test
, you'll be warned of any API changes you need to make.
-
-
Version 1.2 would escalate these warnings to DeprecationWarning
, which is loud by default.
+Version 1.2 would escalate these warnings to subclass DeprecationWarning
, which is loud by default.
-
Version 1.3 would remove the deprecated bits of API entirely.
@@ -505,8 +505,27 @@
Date: 3rd March 2019
+_urls
cache on register()
#6407validators
to accept non-list iterables. #6282RemovedInDRF…Warning
classes to simplify deprecations. #6480Date: 16th Janurary 2019
+Date: 16th Janurary 2019
None
.
+
+
diff --git a/css/bootstrap-responsive.css b/css/bootstrap-responsive.css
old mode 100755
new mode 100644
diff --git a/css/bootstrap.css b/css/bootstrap.css
old mode 100755
new mode 100644
diff --git a/index.html b/index.html
index d418cf921..d9edda6f6 100644
--- a/index.html
+++ b/index.html
@@ -553,7 +553,7 @@ continued development by signing up for a p
REST framework requires the following:
We highly recommend and only officially support the latest patch release of each Python and Django series.
diff --git a/js/bootstrap-2.1.1-min.js b/js/bootstrap-2.1.1-min.js old mode 100755 new mode 100644 diff --git a/mkdocs/search_index.json b/mkdocs/search_index.json index ff5618e07..fcc4a1cdc 100644 --- a/mkdocs/search_index.json +++ b/mkdocs/search_index.json @@ -2,7 +2,7 @@ "docs": [ { "location": "/", - "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\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\nEvery single sign-up helps us make REST framework long-term financially sustainable.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nAuklet\n\n \nRollbar\n\n \nCadre\n\n \nLoad Impact\n\n \nKloudless\n\n \nLights On Software\n\n\n\n\n\n\n\n\nMany thanks to all our \nwonderful sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nAuklet\n, \nRollbar\n, \nCadre\n, \nLoad Impact\n, \nKloudless\n, and \nLights On Software\n.\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.4, 3.5, 3.6, 3.7)\n\n\nDjango (1.11, 2.0, 2.1)\n\n\n\n\nWe \nhighly recommend\n and only officially support the latest patch release of\neach Python and Django series.\n\n\nThe following packages are optional:\n\n\n\n\ncoreapi\n (1.32.0+) - Schema generation support.\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (1.0.1+) - 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 https://github.com/encode/django-rest-framework\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'))\n]\n\n\n\nNote that the URL path can be whatever you want.\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\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\nFor priority support please sign up for a \nprofessional or premium sponsorship plan\n.\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 \u00a9 2011-present, \nEncode OSS Ltd\n.\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\n\n\n\n\nRedistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n\n\n\n\n\nRedistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n\n\n\n\n\nNeither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n\n\n\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\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\nEvery single sign-up helps us make REST framework long-term financially sustainable.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nAuklet\n\n \nRollbar\n\n \nCadre\n\n \nLoad Impact\n\n \nKloudless\n\n \nLights On Software\n\n\n\n\n\n\n\n\nMany thanks to all our \nwonderful sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nAuklet\n, \nRollbar\n, \nCadre\n, \nLoad Impact\n, \nKloudless\n, and \nLights On Software\n.\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.4, 3.5, 3.6, 3.7)\n\n\nDjango (1.11, 2.0, 2.1, 2.2)\n\n\n\n\nWe \nhighly recommend\n and only officially support the latest patch release of\neach Python and Django series.\n\n\nThe following packages are optional:\n\n\n\n\ncoreapi\n (1.32.0+) - Schema generation support.\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (1.0.1+) - 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 https://github.com/encode/django-rest-framework\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'))\n]\n\n\n\nNote that the URL path can be whatever you want.\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\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\nFor priority support please sign up for a \nprofessional or premium sponsorship plan\n.\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 \u00a9 2011-present, \nEncode OSS Ltd\n.\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\n\n\n\n\nRedistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n\n\n\n\n\nRedistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n\n\n\n\n\nNeither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n\n\n\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" }, { @@ -12,7 +12,7 @@ }, { "location": "/#requirements", - "text": "REST framework requires the following: Python (2.7, 3.4, 3.5, 3.6, 3.7) Django (1.11, 2.0, 2.1) We highly recommend and only officially support the latest patch release of\neach Python and Django series. The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (2.1.0+) - Markdown support for the browsable API. django-filter (1.0.1+) - Filtering support. django-crispy-forms - Improved HTML display for filtering. django-guardian (1.1.1+) - Object level permissions support.", + "text": "REST framework requires the following: Python (2.7, 3.4, 3.5, 3.6, 3.7) Django (1.11, 2.0, 2.1, 2.2) We highly recommend and only officially support the latest patch release of\neach Python and Django series. The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (2.1.0+) - Markdown support for the browsable API. django-filter (1.0.1+) - Filtering support. django-crispy-forms - Improved HTML display for filtering. django-guardian (1.1.1+) - Object level permissions support.", "title": "Requirements" }, { @@ -97,7 +97,7 @@ }, { "location": "/tutorial/1-serialization/", - "text": "Tutorial 1: Serialization\n\n\nIntroduction\n\n\nThis tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.\n\n\nThe tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the \nquickstart\n documentation instead.\n\n\n\n\nNote\n: The code for this tutorial is available in the \ntomchristie/rest-framework-tutorial\n repository on GitHub. The completed implementation is also online as a sandbox version for testing, \navailable here\n.\n\n\n\n\nSetting up a new environment\n\n\nBefore we do anything else we'll create a new virtual environment, using \nvirtualenv\n. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.\n\n\nvirtualenv env\nsource env/bin/activate\n\n\n\nNow that we're inside a virtualenv environment, we can install our package requirements.\n\n\npip install django\npip install djangorestframework\npip install pygments # We'll be using this for the code highlighting\n\n\n\nNote:\n To exit the virtualenv environment at any time, just type \ndeactivate\n. For more information see the \nvirtualenv documentation\n.\n\n\nGetting started\n\n\nOkay, we're ready to get coding.\nTo get started, let's create a new project to work with.\n\n\ncd ~\ndjango-admin startproject tutorial\ncd tutorial\n\n\n\nOnce that's done we can create an app that we'll use to create a simple Web API.\n\n\npython manage.py startapp snippets\n\n\n\nWe'll need to add our new \nsnippets\n app and the \nrest_framework\n app to \nINSTALLED_APPS\n. Let's edit the \ntutorial/settings.py\n file:\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n 'snippets.apps.SnippetsConfig',\n)\n\n\n\nOkay, we're ready to roll.\n\n\nCreating a model to work with\n\n\nFor the purposes of this tutorial we're going to start by creating a simple \nSnippet\n model that is used to store code snippets. Go ahead and edit the \nsnippets/models.py\n file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.\n\n\nfrom django.db import models\nfrom pygments.lexers import get_all_lexers\nfrom pygments.styles import get_all_styles\n\nLEXERS = [item for item in get_all_lexers() if item[1]]\nLANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])\nSTYLE_CHOICES = sorted((item, item) for item in get_all_styles())\n\n\nclass Snippet(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n title = models.CharField(max_length=100, blank=True, default='')\n code = models.TextField()\n linenos = models.BooleanField(default=False)\n language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)\n style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)\n\n class Meta:\n ordering = ('created',)\n\n\n\nWe'll also need to create an initial migration for our snippet model, and sync the database for the first time.\n\n\npython manage.py makemigrations snippets\npython manage.py migrate\n\n\n\nCreating a Serializer class\n\n\nThe first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as \njson\n. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the \nsnippets\n directory named \nserializers.py\n and add the following.\n\n\nfrom rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n code = serializers.CharField(style={'base_template': 'textarea.html'})\n linenos = serializers.BooleanField(required=False)\n language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')\n style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Snippet` instance, given the validated data.\n \"\"\"\n return Snippet.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Snippet` instance, given the validated data.\n \"\"\"\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\n\n\nThe first part of the serializer class defines the fields that get serialized/deserialized. The \ncreate()\n and \nupdate()\n methods define how fully fledged instances are created or modified when calling \nserializer.save()\n\n\nA serializer class is very similar to a Django \nForm\n class, and includes similar validation flags on the various fields, such as \nrequired\n, \nmax_length\n and \ndefault\n.\n\n\nThe field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The \n{'base_template': 'textarea.html'}\n flag above is equivalent to using \nwidget=widgets.Textarea\n on a Django \nForm\n class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.\n\n\nWe can actually also save ourselves some time by using the \nModelSerializer\n class, as we'll see later, but for now we'll keep our serializer definition explicit.\n\n\nWorking with Serializers\n\n\nBefore we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.\n\n\npython manage.py shell\n\n\n\nOkay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nsnippet = Snippet(code='foo = \"bar\"\\n')\nsnippet.save()\n\nsnippet = Snippet(code='print \"hello, world\"\\n')\nsnippet.save()\n\n\n\nWe've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.\n\n\nserializer = SnippetSerializer(snippet)\nserializer.data\n# {'id': 2, 'title': u'', 'code': u'print \"hello, world\"\\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into \njson\n.\n\n\ncontent = JSONRenderer().render(serializer.data)\ncontent\n# '{\"id\": 2, \"title\": \"\", \"code\": \"print \\\\\"hello, world\\\\\"\\\\n\", \"linenos\": false, \"language\": \"python\", \"style\": \"friendly\"}'\n\n\n\nDeserialization is similar. First we parse a stream into Python native datatypes...\n\n\nimport io\n\nstream = io.BytesIO(content)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a fully populated object instance.\n\n\nserializer = SnippetSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# OrderedDict([('title', ''), ('code', 'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])\nserializer.save()\n#