diff --git a/.gitignore b/.gitignore
index ae73f8379..2bdf8f7eb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,7 +3,7 @@
*~
.*
-html/
+site/
htmlcov/
coverage/
build/
diff --git a/.travis.yml b/.travis.yml
index a5b6d7d91..6191e7e26 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,28 +1,41 @@
language: python
-python: 2.7
+sudo: false
env:
- - TOX_ENV=flake8
- - TOX_ENV=py3.4-django1.7
- - TOX_ENV=py3.3-django1.7
- - TOX_ENV=py3.2-django1.7
- - TOX_ENV=py2.7-django1.7
- - TOX_ENV=py3.4-django1.6
- - TOX_ENV=py3.3-django1.6
- - TOX_ENV=py3.2-django1.6
- - TOX_ENV=py2.7-django1.6
- - TOX_ENV=py2.6-django1.6
- - TOX_ENV=py3.4-django1.5
- - TOX_ENV=py3.3-django1.5
- - TOX_ENV=py3.2-django1.5
- - TOX_ENV=py2.7-django1.5
- - TOX_ENV=py2.6-django1.5
- - TOX_ENV=py2.7-django1.4
- - TOX_ENV=py2.6-django1.4
+ - TOX_ENV=py27-flake8
+ - TOX_ENV=py27-docs
+ - TOX_ENV=py34-django17
+ - TOX_ENV=py33-django17
+ - TOX_ENV=py32-django17
+ - TOX_ENV=py27-django17
+ - TOX_ENV=py34-django16
+ - TOX_ENV=py33-django16
+ - TOX_ENV=py32-django16
+ - TOX_ENV=py27-django16
+ - TOX_ENV=py26-django16
+ - TOX_ENV=py34-django15
+ - TOX_ENV=py33-django15
+ - TOX_ENV=py32-django15
+ - TOX_ENV=py27-django15
+ - TOX_ENV=py26-django15
+ - TOX_ENV=py27-django14
+ - TOX_ENV=py26-django14
+ - TOX_ENV=py34-djangomaster
+ - TOX_ENV=py33-djangomaster
+ - TOX_ENV=py32-djangomaster
+ - TOX_ENV=py27-djangomaster
+
+matrix:
+ fast_finish: true
+ allow_failures:
+ - env: TOX_ENV=py34-djangomaster
+ - env: TOX_ENV=py33-djangomaster
+ - env: TOX_ENV=py32-djangomaster
+ - env: TOX_ENV=py27-djangomaster
install:
- - "pip install tox --download-cache $HOME/.pip-cache"
+ - pip install tox
script:
- tox -e $TOX_ENV
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a6dd05a0e..698029959 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -75,7 +75,7 @@ You can also use the excellent [`tox`][tox] testing tool to run the tests agains
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 seperate issue without interfering with an ongoing pull requests.
+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.
@@ -101,15 +101,15 @@ There are many great markdown editors that make working with the documentation r
## Building the documentation
-To build the documentation, simply run the `mkdocs.py` script.
+To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
- ./mkdocs.py
+ mkdocs build
This will build the html output into the `html` directory.
-You can build the documentation and open a preview in a browser window by using the `-p` flag.
+You can build the documentation and open a preview in a browser window by using the `serve` command.
- ./mkdocs.py -p
+ mkdocs serve
## Language style
diff --git a/MANIFEST.in b/MANIFEST.in
index d407865fb..d202c86ea 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,4 +1,4 @@
-recursive-include rest_framework/static *.js *.css *.png
+recursive-include rest_framework/static *.js *.css *.png *.eot *.svg *.ttf *.woff
recursive-include rest_framework/templates *.html
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
diff --git a/README.md b/README.md
index 428fb8e9d..c86bb65ff 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,17 @@
# Django REST framework
[![build-status-image]][travis]
+[![pypi-version]][pypi]
**Awesome web-browseable Web APIs.**
-**Note**: Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
+Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
+
+---
+
+**Note**: The incoming 3.0 version has now been merged to the `master` branch on GitHub. For the source of the currently available PyPI version, please see the `2.4.4` tag.
+
+---
# Overview
@@ -27,7 +34,7 @@ There is a live example API for testing purposes, [available here][sandbox].
# Requirements
* Python (2.6.5+, 2.7, 3.2, 3.3, 3.4)
-* Django (1.4.2+, 1.5, 1.6, 1.7)
+* Django (1.4.11+, 1.5.5+, 1.6, 1.7)
# Installation
@@ -175,6 +182,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
+[pypi-version]: https://pypip.in/version/djangorestframework/badge.svg
+[pypi]: https://pypi.python.org/pypi/djangorestframework
[twitter]: https://twitter.com/_tomchristie
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
diff --git a/docs/CNAME b/docs/CNAME
new file mode 100644
index 000000000..4e3328996
--- /dev/null
+++ b/docs/CNAME
@@ -0,0 +1 @@
+www.django-rest-framework.org
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 0ec5bad10..b04858e39 100755
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -1,4 +1,4 @@
-
+source: authentication.py
# Authentication
@@ -168,12 +168,13 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
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
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
- @receiver(post_save, sender=get_user_model())
+ @receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@@ -397,7 +398,7 @@ HTTP digest authentication is a widely implemented scheme that was intended to r
## Django OAuth Toolkit
-The [Django OAuth Toolkit][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][evonove] and uses the excelllent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support.
+The [Django OAuth Toolkit][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][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support.
## Django OAuth2 Consumer
@@ -415,6 +416,10 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism.
+## Djoser
+
+[Djoser][djoser] 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.
+
[cite]: http://jacobian.org/writing/rest-worst-practices/
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
@@ -449,3 +454,4 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
[hawk]: https://github.com/hueniverse/hawk
[mohawk]: http://mohawk.readthedocs.org/en/latest/
[mac]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
+[djoser]: https://github.com/sunscrapers/djoser
diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md
index 94dd59cac..bc3b09fb7 100644
--- a/docs/api-guide/content-negotiation.md
+++ b/docs/api-guide/content-negotiation.md
@@ -1,4 +1,4 @@
-
+source: negotiation.py
# Content negotiation
@@ -29,7 +29,7 @@ The priorities for each of the given media types would be:
If the requested view was only configured with renderers for `YAML` and `HTML`, then REST framework would select whichever renderer was listed first in the `renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting.
-For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
+For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
---
@@ -62,7 +62,7 @@ request when selecting the appropriate parser or renderer.
Select the first parser in the `.parser_classes` list.
"""
return parsers[0]
-
+
def select_renderer(self, request, renderers, format_suffix):
"""
Select the first renderer in the `.renderer_classes` list.
diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md
index e61dcfa90..8e0b1958e 100644
--- a/docs/api-guide/exceptions.md
+++ b/docs/api-guide/exceptions.md
@@ -1,4 +1,4 @@
-
+source: exceptions.py
# Exceptions
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index bfbff2adb..354ec9662 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -1,4 +1,4 @@
-
+source: fields.py
# Serializer fields
@@ -62,7 +62,7 @@ A dictionary of error codes to error messages.
### `widget`
Used only if rendering the field to HTML.
-This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see [the Django documentation on form widgets][django-widgets].
+This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see [the Django documentation on form widgets][django-widgets].
### `label`
@@ -274,7 +274,27 @@ Corresponds to `django.db.models.fields.FloatField`.
## DecimalField
-A decimal representation.
+A decimal representation, represented in Python by a Decimal instance.
+
+Has two required arguments:
+
+- `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.
+
+For example, 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.
+
+**Signature:** `DecimalField(max_digits, decimal_places, coerce_to_string=None)`
Corresponds to `django.db.models.fields.DecimalField`.
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index cfeb43349..83977048f 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -1,4 +1,4 @@
-
+source: filters.py
# Filtering
@@ -26,7 +26,7 @@ For example:
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
-
+
def get_queryset(self):
"""
This view should return a list of all the purchases
@@ -38,7 +38,7 @@ For example:
## Filtering against the URL
-Another style of filtering might involve restricting the queryset based on some part of the URL.
+Another style of filtering might involve restricting the queryset based on some part of the URL.
For example if your URL config contained an entry like this:
@@ -48,7 +48,7 @@ You could then write a view that returned a purchase queryset filtered by the us
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
-
+
def get_queryset(self):
"""
This view should return a list of all the purchases for
@@ -57,7 +57,7 @@ You could then write a view that returned a purchase queryset filtered by the us
username = self.kwargs['username']
return Purchase.objects.filter(purchaser__username=username)
-## Filtering against query parameters
+## Filtering against query parameters
A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.
@@ -65,7 +65,7 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
-
+
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
@@ -113,7 +113,7 @@ For instance, given the previous example, and a product with an id of `4675`, th
http://example.com/api/products/4675/?category=clothing&max_price=10.00
## Overriding the initial queryset
-
+
Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
class PurchasedProductsList(generics.ListAPIView):
@@ -124,7 +124,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
model = Product
serializer_class = ProductSerializer
filter_class = ProductFilter
-
+
def get_queryset(self):
user = self.request.user
return user.purchase_set.all()
@@ -135,7 +135,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
## DjangoFilterBackend
-The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter].
+The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter].
To use REST framework's `DjangoFilterBackend`, first install `django-filter`.
@@ -216,7 +216,7 @@ This is nice, but it exposes the Django's double underscore convention as part o
And now you can execute:
http://example.com/api/products?manufacturer=foo
-
+
For more details on using filter sets see the [django-filter documentation][django-filter-docs].
---
@@ -224,7 +224,7 @@ For more details on using filter sets see the [django-filter documentation][djan
**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][nullbooleanselect].)
+* 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][nullbooleanselect].)
* `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.
@@ -316,7 +316,7 @@ Typically you'd instead control this by setting `order_by` on the initial querys
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.OrderingFilter,)
- ordering = ('username',)
+ ordering = ('username',)
The `ordering` attribute may be either a string or a list/tuple of strings.
diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md
index 76a3367b0..20c1e9952 100644
--- a/docs/api-guide/format-suffixes.md
+++ b/docs/api-guide/format-suffixes.md
@@ -1,4 +1,4 @@
-
+source: urlpatterns.py
# Format suffixes
@@ -7,7 +7,7 @@ used all the time.
>
> — Roy Fielding, [REST discuss mailing list][cite]
-A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.
+A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.
Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.
@@ -21,7 +21,7 @@ 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.
+* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
Example:
@@ -33,7 +33,7 @@ Example:
url(r'^comments/$', views.comment_list),
url(r'^comments/(?P[0-9]+)/$', views.comment_detail)
]
-
+
urlpatterns = 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:
@@ -56,12 +56,12 @@ The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` se
Also note that `format_suffix_patterns` does not support descending into `include` URL patterns.
---
-
+
## Accept headers vs. format suffixes
There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead.
-It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:
+It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:
“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2]
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index b1c4e65ad..648ece827 100755
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -1,5 +1,5 @@
-
-
+source: mixins.py
+ generics.py
# Generic views
@@ -19,8 +19,8 @@ Typically when using the generic views, you'll override the view, and set severa
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
- from rest_framework import generics
- from rest_framework.permissions import IsAdminUser
+ from rest_framework import generics
+ from rest_framework.permissions import IsAdminUser
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
@@ -212,8 +212,6 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
-If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`.
-
## CreateModelMixin
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
@@ -370,6 +368,20 @@ If you are using a mixin across multiple views, you can take this a step further
Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.
+---
+
+# PUT as create
+
+Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not.
+
+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 from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.
+
+If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
+
+---
+
# Third party packages
The following third party packages provide additional generic view implementations.
diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md
new file mode 100644
index 000000000..c3f036b75
--- /dev/null
+++ b/docs/api-guide/metadata.md
@@ -0,0 +1,103 @@
+
+
+# Metadata
+
+> [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
+>
+> — [RFC7231, Section 4.3.7.][cite]
+
+REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information.
+
+There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information.
+
+Here's an example response that demonstrates the information that is returned by default.
+
+ HTTP 200 OK
+ Allow: GET, POST, HEAD, OPTIONS
+ Content-Type: application/json
+
+ {
+ "name": "To Do List",
+ "description": "List existing 'To Do' items, or create a new item.",
+ "renders": [
+ "application/json",
+ "text/html"
+ ],
+ "parses": [
+ "application/json",
+ "application/x-www-form-urlencoded",
+ "multipart/form-data"
+ ],
+ "actions": {
+ "POST": {
+ "note": {
+ "type": "string",
+ "required": false,
+ "read_only": false,
+ "label": "title",
+ "max_length": 100
+ }
+ }
+ }
+ }
+
+## Setting the metadata scheme
+
+You can set the metadata class globally using the `'DEFAULT_METADATA_CLASS'` settings key:
+
+ REST_FRAMEWORK = {
+ 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
+ }
+
+Or you can set the metadata class individually for a view:
+
+ class APIRoot(APIView):
+ metadata_class = APIRootMetadata
+
+ def get(self, request, format=None):
+ return Response({
+ ...
+ })
+
+The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class.
+
+## Creating schema endpoints
+
+If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so.
+
+For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.
+
+ @list_route(methods=['GET'])
+ def schema(self, request):
+ meta = self.metadata_class()
+ data = meta.determine_metadata(request, self)
+ return Response(data)
+
+There are a couple of reasons that you might choose to take this approach, including that `OPTIONS` responses [are not cacheable][no-options].
+
+---
+
+# Custom metadata classes
+
+If you want to provide a custom metadata class you should override `BaseMetadata` and implement the `determine_metadata(self, request, view)` method.
+
+Useful things that you might want to do could include returning schema information, using a format such as [JSON schema][json-schema], or returning debug information to admin users.
+
+## Example
+
+The following class could be used to limit the information that is returned to `OPTIONS` requests.
+
+ class MinimalMetadata(BaseMetadata):
+ """
+ Don't include field and other information for `OPTIONS` requests.
+ Just return the name and description.
+ """
+ def determine_metadata(self, request, view):
+ return {
+ 'name': view.get_view_name(),
+ 'description': view.get_view_description()
+ }
+
+[cite]: http://tools.ietf.org/html/rfc7231#section-4.3.7
+[no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS
+[json-schema]: http://json-schema.org/
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index e57aed1a9..9b7086c54 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -1,4 +1,4 @@
-
+source: pagination.py
# Pagination
@@ -6,7 +6,7 @@
>
> — [Django documentation][cite]
-REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.
+REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.
## Paginating basic data
@@ -33,7 +33,7 @@ The `context` argument of the `PaginationSerializer` class may optionally includ
request = RequestFactory().get('/foobar')
serializer = PaginationSerializer(instance=page, context={'request': request})
serializer.data
- # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
+ # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
We could now return that data in a `Response` object, and it would be rendered into the correct media type.
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 72a4af643..42d77b223 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -1,4 +1,4 @@
-
+source: parsers.py
# Parsers
@@ -161,7 +161,7 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa
## Example
-The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request.
+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):
"""
@@ -197,4 +197,4 @@ The following third party packages are also available.
[juanriaza]: https://github.com/juanriaza
[vbabiy]: https://github.com/vbabiy
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
-[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
\ No newline at end of file
+[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index e867a4569..f068f0f72 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -1,4 +1,4 @@
-
+source: permissions.py
# Permissions
@@ -12,7 +12,7 @@ Permission checks are always run at the very start of the view, before any other
## How permissions are determined
-Permissions in REST framework are always defined as a list of permission classes.
+Permissions in REST framework are always defined as a list of permission classes.
Before running the main body of the view each permission in the list is checked.
If any permission check fails an `exceptions.PermissionDenied` exception will be raised, and the main body of the view will not run.
@@ -146,7 +146,13 @@ As with `DjangoModelPermissions`, this permission must only be applied to views
Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well.
-As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. Note that if you add a custom `view` permission for `GET`, `HEAD` and `OPTIONS` requests, you'll probably also want to consider adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.
+As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details.
+
+---
+
+**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests, you'll want to consider also adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.
+
+---
## TokenHasReadWriteScope
@@ -183,11 +189,7 @@ If you need to test if a request is a read operation or a write operation, you s
---
-**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.
-
-As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
-
-For more details see the [2.2 release announcement][2.2-announcement].
+**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default.
---
@@ -218,9 +220,9 @@ As well as global permissions, that are run against all incoming requests, you c
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
- if request.method in permissions.SAFE_METHODS:
+ if request.method in permissions.SAFE_METHODS:
return True
-
+
# Instance must have an attribute named `owner`.
return obj.owner == request.user
diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md
index cc4f55851..ad981b2bb 100644
--- a/docs/api-guide/relations.md
+++ b/docs/api-guide/relations.md
@@ -1,4 +1,4 @@
-
+source: relations.py
# Serializer relations
@@ -33,7 +33,7 @@ In order to explain the various types of relational fields, we'll use a couple o
class Meta:
unique_together = ('album', 'order')
order_by = 'order'
-
+
def __unicode__(self):
return '%d: %s' % (self.order, self.title)
@@ -42,10 +42,10 @@ In order to explain the various types of relational fields, we'll use a couple o
`RelatedField` may be used to represent the target of the relationship using its `__unicode__` method.
For example, the following serializer.
-
+
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.RelatedField(many=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -74,10 +74,10 @@ This field is read only.
`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
For example, the following serializer:
-
+
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -108,11 +108,11 @@ By default this field is read-write, although you can change this behavior using
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
For example, the following serializer:
-
+
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True,
view_name='track-detail')
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -146,11 +146,11 @@ By default this field is read-write, although you can change this behavior using
`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
For example, the following serializer:
-
+
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SlugRelatedField(many=True, read_only=True,
slug_field='title')
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -202,7 +202,7 @@ This field is always read-only.
**Arguments**:
-* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this wil be a string with the format `-detail`. **required**.
+* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**.
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
@@ -222,10 +222,10 @@ For example, the following serializer:
class Meta:
model = Track
fields = ('order', 'title')
-
+
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -262,7 +262,7 @@ For, example, we could define a relational field, to serialize a track to a cust
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackListingField(many=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -302,7 +302,7 @@ If you have not set a related name for the reverse relationship, you'll need to
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
- fields = ('track_set', ...)
+ fields = ('track_set', ...)
See the Django documentation on [reverse relationships][reverse-relationships] for more details.
@@ -315,14 +315,14 @@ For example, given the following model for a tag, which has a generic relationsh
class TaggedItem(models.Model):
"""
Tags arbitrary model instances using a generic relation.
-
+
See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
"""
tag_name = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
tagged_object = GenericForeignKey('content_type', 'object_id')
-
+
def __unicode__(self):
return self.tag
@@ -353,7 +353,7 @@ We could define a custom field that could be used to serialize tagged instances,
def to_native(self, value):
"""
Serialize tagged objects to a simple textual representation.
- """
+ """
if isinstance(value, Bookmark):
return 'Bookmark: ' + value.url
elif isinstance(value, Note):
@@ -366,7 +366,7 @@ If you need the target of the relationship to have a nested representation, you
"""
Serialize bookmark instances using a bookmark serializer,
and note instances using a note serializer.
- """
+ """
if isinstance(value, Bookmark):
serializer = BookmarkSerializer(value)
elif isinstance(value, Note):
@@ -391,7 +391,7 @@ to ``True``.
## Advanced Hyperlinked fields
-If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`.
+If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`.
There are two methods you'll need to override.
@@ -411,7 +411,7 @@ May raise an `ObjectDoesNotExist` exception.
### Example
-For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:
+For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:
class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
def get_url(self, obj, view_name, request, format):
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 20eed70d6..035ec1d27 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -1,4 +1,4 @@
-
+source: renderers.py
# Renderers
@@ -74,37 +74,18 @@ If your API includes views that can serve both regular webpages and API response
Renders the request data into `JSON`, using utf-8 encoding.
-Note that non-ascii characters will be rendered using JSON's `\uXXXX` character escape. For example:
+Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:
- {"unicode black star": "\u2605"}
+ {"unicode black star":"★","value":999}
The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`.
{
- "unicode black star": "\u2605"
+ "unicode black star": "★",
+ "value": 999
}
-**.media_type**: `application/json`
-
-**.format**: `'.json'`
-
-**.charset**: `None`
-
-## UnicodeJSONRenderer
-
-Renders the request data into `JSON`, using utf-8 encoding.
-
-Note that non-ascii characters will not be character escaped. For example:
-
- {"unicode black star": "★"}
-
-The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`.
-
- {
- "unicode black star": "★"
- }
-
-Both the `JSONRenderer` and `UnicodeJSONRenderer` styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON.
+The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys.
**.media_type**: `application/json`
@@ -134,7 +115,7 @@ The `jsonp` approach is essentially a browser hack, and is [only appropriate for
## YAMLRenderer
-Renders the request data into `YAML`.
+Renders the request data into `YAML`.
Requires the `pyyaml` package to be installed.
@@ -150,7 +131,7 @@ Note that non-ascii characters will be rendered using `\uXXXX` character escape.
## UnicodeYAMLRenderer
-Renders the request data into `YAML`.
+Renders the request data into `YAML`.
Requires the `pyyaml` package to be installed.
@@ -203,7 +184,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return Response({'user': self.object}, template_name='user_detail.html')
-
+
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
@@ -224,7 +205,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
@api_view(('GET',))
@renderer_classes((StaticHTMLRenderer,))
- def simple_html_view(request):
+ def simple_html_view(request):
data = '
Hello, world
'
return Response(data)
@@ -319,7 +300,7 @@ The following is an example plaintext renderer that will return a response with
class PlainTextRenderer(renderers.BaseRenderer):
media_type = 'text/plain'
format = 'txt'
-
+
def render(self, data, media_type=None, renderer_context=None):
return data.encode(self.charset)
@@ -359,7 +340,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
* Provide either flat or nested representations from the same endpoint, depending on the requested media type.
* Serve both regular HTML webpages, and JSON based API responses from the same endpoints.
* Specify multiple types of HTML representation for API clients to use.
-* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
+* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
## Varying behaviour by media type
diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md
index 0696fedf6..8713fa2a6 100644
--- a/docs/api-guide/requests.md
+++ b/docs/api-guide/requests.md
@@ -1,4 +1,4 @@
-
+source: request.py
# Requests
@@ -49,6 +49,20 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
---
+# Content negotiation
+
+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.
+
+## .accepted_renderer
+
+The renderer instance what was selected by the content negotiation stage.
+
+## .accepted_media_type
+
+A string representing the media type that was accepted by the content negotiation stage.
+
+---
+
# Authentication
REST framework provides flexible, per-request authentication, that gives you the ability to:
@@ -91,7 +105,7 @@ REST framework supports a few browser enhancements such as browser-based `PUT`,
Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported.
-For more information see the [browser enhancements documentation].
+For more information see the [browser enhancements documentation].
## .content_type
@@ -101,7 +115,7 @@ You won't typically need to directly access the request's content type, as you'l
If you do need to access the content type of the request you should use the `.content_type` property in preference to using `request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for browser-based non-form content.
-For more information see the [browser enhancements documentation].
+For more information see the [browser enhancements documentation].
## .stream
@@ -111,7 +125,7 @@ You won't typically need to directly access the request's content, as you'll nor
If you do need to access the raw content directly, you should use the `.stream` property in preference to using `request.content`, as it provides transparent support for browser-based non-form content.
-For more information see the [browser enhancements documentation].
+For more information see the [browser enhancements documentation].
---
diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md
index 5a42aa923..97f312710 100644
--- a/docs/api-guide/responses.md
+++ b/docs/api-guide/responses.md
@@ -1,4 +1,4 @@
-
+source: response.py
# Responses
@@ -90,6 +90,6 @@ The `Response` class extends `SimpleTemplateResponse`, and all the usual attribu
As with any other `TemplateResponse`, this method is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type, renderer_context)` method on the `accepted_renderer` instance.
You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle.
-
+
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/
[statuscodes]: status-codes.md
diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md
index 383eca4ce..71fb83f9e 100644
--- a/docs/api-guide/reverse.md
+++ b/docs/api-guide/reverse.md
@@ -1,4 +1,4 @@
-
+source: reverse.py
# Returning URLs
@@ -30,7 +30,7 @@ You should **include the request as a keyword argument** to the function, for ex
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from django.utils.timezone import now
-
+
class APIRootView(APIView):
def get(self, request):
year = now().year
diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md
index 61a476b8b..080230faf 100644
--- a/docs/api-guide/routers.md
+++ b/docs/api-guide/routers.md
@@ -1,4 +1,4 @@
-
+source: routers.py
# Routers
@@ -56,10 +56,10 @@ For example, given a method like this on the `UserViewSet` class:
from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import detail_route
-
+
class UserViewSet(ModelViewSet):
...
-
+
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
@@ -228,7 +228,7 @@ For another example of setting the `.routes` attribute, see the source code for
## Advanced custom routers
-If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
+If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index a3694510e..2d0ff79a4 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -1,4 +1,4 @@
-
+source: serializers.py
# Serializers
@@ -21,7 +21,7 @@ Let's start by creating a simple object we can use for example purposes:
self.email = email
self.content = content
self.created = created or datetime.datetime.now()
-
+
comment = Comment(email='leila@example.com', content='foo bar')
We'll declare a serializer that we can use to serialize and deserialize `Comment` objects.
@@ -45,7 +45,7 @@ Declaring a serializer looks very similar to declaring a form:
instance.content = attrs.get('content', instance.content)
instance.created = attrs.get('created', instance.created)
return instance
- return Comment(**attrs)
+ return Comment(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
@@ -83,8 +83,8 @@ If you need to customize the serialized value of a particular field, you can do
These methods are essentially the reverse of `validate_` (see *Validation* below.)
## Deserializing objects
-
-Deserialization is similar. First we parse a stream into Python native datatypes...
+
+Deserialization is similar. First we parse a stream into Python native datatypes...
from StringIO import StringIO
from rest_framework.parsers import JSONParser
@@ -174,7 +174,7 @@ To save the deserialized objects created by a serializer, call the `.save()` met
The default behavior of the method is to simply call `.save()` on the deserialized object instance. You can override the default save behaviour by overriding the `.save_object(obj)` method on the serializer class.
-The generic views provided by REST framework call the `.save()` method when updating or creating entities.
+The generic views provided by REST framework call the `.save()` method when updating or creating entities.
## Dealing with nested objects
@@ -288,12 +288,12 @@ By default the serializer class will use the `id` key on the incoming data to de
slug = serializers.CharField(max_length=100)
created = serializers.DateTimeField()
... # Various other fields
-
+
def get_identity(self, data):
"""
This hook is required for bulk update.
We need to override the default, to use the slug as the identity.
-
+
Note that the data has not yet been validated at this point,
so we need to deal gracefully with incorrect datatypes.
"""
@@ -361,7 +361,7 @@ The `depth` option should be set to an integer value that indicates the depth of
If you want to customize the way the serialization is done (e.g. using `allow_add_remove`) you'll need to define the field yourself.
-## Specifying which fields should be read-only
+## Specifying which fields should be read-only
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
@@ -371,9 +371,9 @@ You may wish to specify multiple fields as read-only. Instead of adding each fi
fields = ('id', 'account_name', 'users', 'created')
read_only_fields = ('account_name',)
-Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
+Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
-## Specifying which fields should be write-only
+## Specifying which fields should be write-only
You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the `write_only=True` attribute, you may use the `write_only_fields` Meta option, like so:
@@ -387,12 +387,12 @@ You may wish to specify multiple fields as write-only. Instead of adding each f
"""
Instantiate a new User instance.
"""
- assert instance is None, 'Cannot update users with CreateUserSerializer'
+ assert instance is None, 'Cannot update users with CreateUserSerializer'
user = User(email=attrs['email'], username=attrs['username'])
user.set_password(attrs['password'])
return user
-
-## Specifying fields explicitly
+
+## Specifying fields explicitly
You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class.
@@ -413,6 +413,16 @@ Alternative representations include serializing using hyperlinks, serializing co
For full details see the [serializer relations][relations] documentation.
+## Inheritance of the 'Meta' class
+
+The inner `Meta` class on serializers is not inherited from parent classes by default. This is the same behaviour as with Django's `Model` and `ModelForm` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example:
+
+ class AccountSerializer(MyBaseSerializer):
+ class Meta(MyBaseSerializer.Meta):
+ model = Account
+
+Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly.
+
---
# HyperlinkedModelSerializer
@@ -514,10 +524,10 @@ For example, if you wanted to be able to set which fields should be used by a se
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
-
+
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
-
+
if fields:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
@@ -540,7 +550,7 @@ This would then allow you to do the following:
## Customising the default fields
-The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.
+The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.
For more advanced customization than simply changing the default serializer class you can override various `get__field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`.
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 27a091633..0aa4b6a97 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -1,4 +1,4 @@
-
+source: settings.py
# Settings
@@ -74,7 +74,7 @@ Default:
#### DEFAULT_PERMISSION_CLASSES
-A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.
+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:
@@ -154,13 +154,13 @@ Default: `None`
### SEARCH_PARAM
-The name of a query paramater, which can be used to specify the search term used by `SearchFilter`.
+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 paramater, which can be used to specify the ordering of results returned by `OrderingFilter`.
+The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`.
Default: `ordering`
@@ -265,7 +265,7 @@ A format string that should be used by default for rendering the output of `Date
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
-Default: `None`
+Default: `'iso-8601'`
#### DATETIME_INPUT_FORMATS
@@ -281,7 +281,7 @@ A format string that should be used by default for rendering the output of `Date
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
-Default: `None`
+Default: `'iso-8601'`
#### DATE_INPUT_FORMATS
@@ -297,7 +297,7 @@ A format string that should be used by default for rendering the output of `Time
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
-Default: `None`
+Default: `'iso-8601'`
#### TIME_INPUT_FORMATS
@@ -309,6 +309,46 @@ Default: `['iso-8601']`
---
+## Encodings
+
+#### UNICODE_JSON
+
+When set to `True`, JSON responses will allow unicode characters in responses. For example:
+
+ {"unicode black star":"★"}
+
+When set to `False`, JSON responses will escape non-ascii characters, like so:
+
+ {"unicode black star":"\u2605"}
+
+Both styles conform to [RFC 4627][rfc4627], 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][heroku-minified-json].
+
+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`
+
+---
+
## View names and descriptions
**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.**
@@ -359,6 +399,12 @@ This should be a function with the following signature:
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`.
@@ -378,4 +424,6 @@ An integer of 0 or more, that may be used to specify the number of application p
Default: `None`
[cite]: http://www.python.org/dev/peps/pep-0020/
+[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt
+[heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses
[strftime]: http://docs.python.org/2/library/time.html#time.strftime
diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md
index 64c464349..d81e092c5 100644
--- a/docs/api-guide/status-codes.md
+++ b/docs/api-guide/status-codes.md
@@ -1,4 +1,4 @@
-
+source: status.py
# Status Codes
@@ -27,7 +27,7 @@ The module also includes a set of helper functions for testing if a status code
url = reverse('index')
response = self.client.get(url)
self.assertTrue(status.is_success(response.status_code))
-
+
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
and [RFC 6585][rfc6585].
@@ -51,7 +51,7 @@ This class of status code indicates that the client's request was successfully r
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT
-## Redirection - 3xx
+## Redirection - 3xx
This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md
index 72c339613..d059fdab5 100644
--- a/docs/api-guide/testing.md
+++ b/docs/api-guide/testing.md
@@ -1,4 +1,4 @@
-
+source: test.py
# Testing
@@ -170,7 +170,7 @@ This can be a useful shortcut if you're testing the API but don't want to have t
To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`.
- client.force_authenticate(user=None)
+ client.force_authenticate(user=None)
## CSRF validation
@@ -197,7 +197,7 @@ You can use any of REST framework's test case classes as you would for the regul
from django.core.urlresolvers import reverse
from rest_framework import status
- from rest_framework.test import APITestCase
+ from rest_framework.test import APITestCase
class AccountTests(APITestCase):
def test_create_account(self):
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index 832304f15..3f668867c 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -1,4 +1,4 @@
-
+source: throttling.py
# Throttling
@@ -74,7 +74,7 @@ If you need to strictly identify unique client IP addresses, you'll need to firs
It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
-Further context on how the `X-Forwarded-For` header works, and identifing a remote client IP can be [found here][identifing-clients].
+Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifing-clients].
## Setting up the cache
@@ -83,9 +83,9 @@ The throttle classes provided by REST framework use Django's cache backend. You
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')
+ cache = get_cache('alternate')
-You'll need to rememeber to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
+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.
---
@@ -147,15 +147,15 @@ For example, given the following views...
class ContactListView(APIView):
throttle_scope = 'contacts'
...
-
+
class ContactDetailView(ApiView):
throttle_scope = 'contacts'
...
- class UploadView(APIView):
+ class UploadView(APIView):
throttle_scope = 'uploads'
...
-
+
...and the following settings.
REST_FRAMEWORK = {
@@ -178,6 +178,8 @@ To create a custom throttle, override `BaseThrottle` and implement `.allow_reque
Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`.
+If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response.
+
## Example
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md
new file mode 100644
index 000000000..ac2f32485
--- /dev/null
+++ b/docs/api-guide/validators.md
@@ -0,0 +1,225 @@
+
+
+# Validators
+
+> Validators can be useful for re-using validation logic between different types of fields.
+>
+> — [Django documentation][cite]
+
+Most 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.
+
+However, 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.
+
+## Validation in REST framework
+
+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):
+ time_raised = models.DateTimeField(default=timezone.now, editable=False)
+ reference = models.CharField(unique=True, max_length=20)
+ description = models.TextField()
+
+Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`:
+
+ class CustomerReportSerializer(serializers.ModelSerializer):
+ class Meta:
+ 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))
+ CustomerReportSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ time_raised = DateTimeField(read_only=True)
+ reference = CharField(max_length=20, validators=[])
+ 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.
+
+---
+
+## UniqueValidator
+
+This validator can be used to enforce the `unique=True` constraint on model fields.
+It 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(
+ max_length=100,
+ validators=[UniqueValidator(queryset=BlogPost.objects.all())]
+ )
+
+## UniqueTogetherValidator
+
+This validator can be used to enforce `unique_together` constraints on model instances.
+It has two required arguments, and a single optional `messages` argument:
+
+* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
+* `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields 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):
+ # ...
+ class Meta:
+ # ToDo items belong to a parent list, and have an ordering defined
+ # by the 'position' field. No two items in a given list may share
+ # the same position.
+ validators = [
+ UniqueTogetherValidator(
+ queryset=ToDoItem.objects.all(),
+ fields=('list', 'position')
+ )
+ ]
+
+---
+
+**Note**: The `UniqueTogetherValidation` class always imposes an implicit constraint that all the fields it applies 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.
+
+---
+
+## UniqueForDateValidator
+
+## UniqueForMonthValidator
+
+## UniqueForYearValidator
+
+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):
+ # ...
+ class Meta:
+ # Blog posts should have a slug that is unique for the current year.
+ validators = [
+ UniqueForYearValidator(
+ queryset=BlogPostItem.objects.all(),
+ field='slug',
+ date_field='published'
+ )
+ ]
+
+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 `UniqueForValidation` 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.
+
+---
+
+# Advanced 'default' argument usage
+
+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=…` 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(
+ default=CurrentUserDefault()
+ )
+
+#### 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(
+ read_only=True,
+ default=CreateOnlyDefault(timezone.now)
+ )
+
+---
+
+# Writing custom validators
+
+You can use any of Django's existing validators, or write your own custom validators.
+
+## Function based
+
+A validator may be any callable that raises a `serializers.ValidationError` on failure.
+
+ def even_number(value):
+ if value % 2 != 0:
+ raise serializers.ValidationError('This field must be an even number.')
+
+## Class based
+
+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:
+ def __init__(self, base):
+ self.base = base
+
+ def __call__(self, value):
+ if value % self.base != 0
+ message = 'This field must be a multiple of %d.' % self.base
+ 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):
+ # Determine if this is an update or a create operation.
+ # In `__call__` we can then use that information to modify the validation behavior.
+ self.is_update = serializer_field.parent.instance is not None
+
+[cite]: https://docs.djangoproject.com/en/dev/ref/validators/
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 194a7a6b3..31c62682f 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -1,4 +1,5 @@
-
+source: decorators.py
+ views.py
# Class Based Views
@@ -26,7 +27,7 @@ For example:
class ListUsers(APIView):
"""
View to list all users in the system.
-
+
* Requires token authentication.
* Only admin users are able to access this view.
"""
@@ -54,7 +55,7 @@ The following attributes control the pluggable aspects of API views.
### .permission_classes
-### .content_negotiation_class
+### .content_negotiation_class
## API policy instantiation methods
diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md
index 9030e3ee0..9249d8756 100644
--- a/docs/api-guide/viewsets.md
+++ b/docs/api-guide/viewsets.md
@@ -1,4 +1,4 @@
-
+source: viewsets.py
# ViewSets
diff --git a/docs/css/default.css b/docs/css/default.css
index 7f3acfed2..8c9cd5363 100644
--- a/docs/css/default.css
+++ b/docs/css/default.css
@@ -181,7 +181,7 @@ body{
}
.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{
- color: white;
+ color: white;
}
.nav-list > .active > a, .navbar .navbar-inner .nav li a:hover {
@@ -190,8 +190,20 @@ body{
}
.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{
- color: #A30000;
+ color: #A30000;
}
+
+.dropdown-menu .active > a,
+.dropdown-menu .active > a:hover {
+ background-image: none;
+}
+
+.navbar-inverse .nav .dropdown .active > a,
+.navbar-inverse .nav .dropdown .active > a:hover,
+.navbar-inverse .nav .dropdown .active > a:focus {
+ background-color: #eeeeee;
+}
+
.navbar .navbar-inner .dropdown-menu li a:hover{
background: #eeeeee;
color: #c20000;
diff --git a/docs/index.md b/docs/index.md
index b18b71d20..9312bb2fd 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -9,6 +9,10 @@
---
+**Note**: The incoming 3.0 version has now been merged to the `master` branch on GitHub. For the source of the currently available PyPI version, please see the `2.4.4` tag.
+
+---
+
-
Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
@@ -43,14 +44,12 @@ Some reasons you might want to use REST framework:
**Above**: *Screenshot from the browsable API*
-----
-
## Requirements
REST framework requires the following:
* Python (2.6.5+, 2.7, 3.2, 3.3, 3.4)
-* Django (1.4.2+, 1.5, 1.6, 1.7)
+* Django (1.4.11+, 1.5.5+, 1.6, 1.7)
The following packages are optional:
@@ -173,6 +172,7 @@ The API guide is your complete reference manual to all the functionality provide
* [Serializers][serializers]
* [Serializer fields][fields]
* [Serializer relations][relations]
+
* [Authentication][authentication]
* [Permissions][permissions]
* [Throttling][throttling]
@@ -294,6 +294,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[serializers]: api-guide/serializers.md
[fields]: api-guide/fields.md
[relations]: api-guide/relations.md
+[validation]: api-guide/validation.md
[authentication]: api-guide/authentication.md
[permissions]: api-guide/permissions.md
[throttling]: api-guide/throttling.md
diff --git a/docs/requirements.txt b/docs/requirements.txt
deleted file mode 100644
index a91fb9785..000000000
--- a/docs/requirements.txt
+++ /dev/null
@@ -1 +0,0 @@
-markdown>=2.1.0
diff --git a/docs/template.html b/docs/template.html
deleted file mode 100644
index bb3ae221a..000000000
--- a/docs/template.html
+++ /dev/null
@@ -1,238 +0,0 @@
-
-
-
-
- {{ title }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/docs/topics/2.2-announcement.md b/docs/topics/2.2-announcement.md
index a997c7829..1df52cff2 100644
--- a/docs/topics/2.2-announcement.md
+++ b/docs/topics/2.2-announcement.md
@@ -42,7 +42,7 @@ The 2.2 release makes a few changes to the API, in order to make it more consist
The `ManyRelatedField()` style is being deprecated in favor of a new `RelatedField(many=True)` syntax.
-For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:
+For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:
class UserSerializer(serializers.HyperlinkedModelSerializer):
questions = serializers.PrimaryKeyRelatedField(many=True)
@@ -58,10 +58,10 @@ The change also applies to serializers. If you have a nested serializer, you sh
class Meta:
model = Track
fields = ('name', 'duration')
-
+
class AlbumSerializer(serializer.ModelSerializer):
tracks = TrackSerializer(many=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -87,7 +87,7 @@ For example, is a user account has an optional foreign key to a company, that yo
This is in line both with the rest of the serializer fields API, and with Django's `Form` and `ModelForm` API.
-Using `required` throughout the serializers API means you won't need to consider if a particular field should take `blank` or `null` arguments instead of `required`, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.
+Using `required` throughout the serializers API means you won't need to consider if a particular field should take `blank` or `null` arguments instead of `required`, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.
The `null=True` argument will continue to function, and will imply `required=False`, but will raise a `PendingDeprecationWarning`.
diff --git a/docs/topics/2.3-announcement.md b/docs/topics/2.3-announcement.md
index 7c800afa0..9c9f3e9f6 100644
--- a/docs/topics/2.3-announcement.md
+++ b/docs/topics/2.3-announcement.md
@@ -27,7 +27,7 @@ As an example of just how simple REST framework APIs can now be, here's an API w
class GroupViewSet(viewsets.ModelViewSet):
model = Group
-
+
# Routers provide an easy way of automatically determining the URL conf
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
@@ -197,13 +197,13 @@ Usage of the old-style attributes continues to be supported, but will raise a `P
For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implementation.
-## ModelSerializers and reverse relationships
+## ModelSerializers and reverse relationships
The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed.
In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For reverse relationships `model_field` will be `None`.
-The old-style signature will continue to function but will raise a `PendingDeprecationWarning`.
+The old-style signature will continue to function but will raise a `PendingDeprecationWarning`.
## View names and descriptions
@@ -211,7 +211,7 @@ The mechanics of how the names and descriptions used in the browseable API are g
If you've been customizing this behavior, for example perhaps to use `rst` markup for the browseable API, then you'll need to take a look at the implementation to see what updates you need to make.
-Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.
+Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.
---
diff --git a/docs/topics/2.4-announcement.md b/docs/topics/2.4-announcement.md
index 8e4f3bb23..f38c743c0 100644
--- a/docs/topics/2.4-announcement.md
+++ b/docs/topics/2.4-announcement.md
@@ -23,7 +23,7 @@ The documentation has previously stated that usage of the more explicit style is
Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the `.model` shortcut. However we firmly believe that it is the right trade-off to make.
-Removing the shortcut takes away an unneccessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.
+Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.
The `DEFAULT_MODEL_SERIALIZER_CLASS` API setting is now also deprecated.
diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md
new file mode 100644
index 000000000..6a662326b
--- /dev/null
+++ b/docs/topics/3.0-announcement.md
@@ -0,0 +1,890 @@
+## Pre-release notes:
+
+The 3.0 release is now in beta and ready for final testing. You can install the development version directly from GitHub like so:
+
+ pip install https://github.com/tomchristie/django-rest-framework/archive/3.0-beta.zip
+
+Currently the only known remaining blockers are documentation issues and tickets. Any critical bugs raised in the next week or two will be resolved for the 3.0 release, but otherwise consider this as code-complete.
+
+Please work through this document throughly in order to understand the API differences that exist between 2.4 and 3.0.
+
+**Your feedback on the upgrade process and 3.0 changes is hugely important!**
+
+Please do get in touch via twitter, IRC, a GitHub ticket, or the discussion group.
+
+---
+
+# REST framework 3.0
+
+The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.
+
+This release is incremental in nature. There *are* some breaking API changes, and upgrading *will* require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.
+
+The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.
+
+## New features
+
+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][mixins.py] 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](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "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.
+
+Below is an in-depth guide to the API changes and migration notes for 3.0.
+
+---
+
+## Request objects
+
+#### 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...
+ ExampleSerializer(data=request.data)
+
+Instead of passing the files argument separately:
+
+ # Don't do this...
+ ExampleSerializer(data=request.DATA, files=request.FILES)
+
+
+The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`.
+
+## Serializers
+
+#### Single-step object creation.
+
+Previously the serializers used a two-step object creation, as follows:
+
+1. Validating the data would create an object instance. This instance would be available as `serializer.object`.
+2. 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:
+
+1. Validating the data makes the cleaned data available as `serializer.validated_data`.
+2. 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 replaced with two separate methods, `.create()` and `.update()`.
+
+These methods also replace the optional `.save_object()` method, which no longer exists.
+
+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.
+
+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):
+ if instance:
+ # Update existing instance
+ instance.title = attrs.get('title', instance.title)
+ instance.code = attrs.get('code', instance.code)
+ instance.linenos = attrs.get('linenos', instance.linenos)
+ instance.language = attrs.get('language', instance.language)
+ instance.style = attrs.get('style', instance.style)
+ return instance
+
+ # Create new instance
+ return Snippet(**attrs)
+
+This would now be split out into two separate methods.
+
+ def update(self, instance, validated_data):
+ instance.title = validated_data.get('title', instance.title)
+ instance.code = validated_data.get('code', instance.code)
+ instance.linenos = validated_data.get('linenos', instance.linenos)
+ instance.language = validated_data.get('language', instance.language)
+ instance.style = validated_data.get('style', instance.style)
+ instance.save()
+ return instance
+
+ def create(self, validated_data):
+ return Snippet.objects.create(**validated_data)
+
+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():
+ name = serializer.object.name # Inspect validated field data.
+ logging.info('Creating ticket "%s"' % name)
+ serializer.object.user = request.user # Include the user when saving.
+ serializer.save()
+
+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():
+ name = serializer.validated_data['name'] # Inspect validated field data.
+ logging.info('Creating ticket "%s"' % name)
+ serializer.save(user=request.user) # Include the user when saving.
+
+#### 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 are always 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_`.
+
+The `validate_` 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):
+ if attrs['score'] % 10 != 0:
+ raise serializers.ValidationError('This field should be a multiple of ten.')
+ 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):
+ if value % 10 != 0:
+ raise serializers.ValidationError('This field should be a multiple of ten.')
+ 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_` 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):
+ # serializer.errors == {'non_field_errors': ['A non field error']}
+ 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):
+ # serializer.errors == {'my_field': ['A field error']}
+ 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.
+
+#### 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.
+
+It's important to note that this change also means that the model `.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.
+
+#### 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()
+ AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.
+
+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):
+ profile = ProfileSerializer()
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'profile')
+
+ def create(self, validated_data):
+ profile_data = validated_data.pop('profile')
+ user = User.objects.create(**validated_data)
+ Profile.objects.create(user=user, **profile_data)
+ return user
+
+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):
+ location = models.CharField(max_length=100)
+ rating = models.IntegerField()
+ created_by = models.ForeignKey(User)
+
+Let's create a simple `ModelSerializer` class corresponding to the `LocationRating` model.
+
+ class LocationRatingSerializer(serializer.ModelSerializer):
+ class Meta:
+ 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
+ LocationRatingSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ location = CharField(max_length=100)
+ rating = IntegerField()
+ 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):
+ class Meta:
+ model = MyModel
+ fields = ('id', 'email', 'notes', 'is_admin')
+ extra_kwargs = {
+ 'is_admin': {'write_only': True}
+ }
+
+Alternatively, specify the field explicitly on the serializer class:
+
+ class MySerializer(serializer.ModelSerializer):
+ is_admin = serializers.BooleanField(write_only=True)
+
+ class Meta:
+ model = MyModel
+ 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):
+ class Meta:
+ model = MyModel
+ fields = ('url', 'email', 'notes', 'is_admin')
+ extra_kwargs = {
+ 'url': {'lookup_field': 'uuid'}
+ }
+
+Alternatively, specify the field explicitly on the serializer class:
+
+ class MySerializer(serializer.HyperlinkedModelSerializer):
+ url = serializers.HyperlinkedIdentityField(
+ view_name='mymodel-detail',
+ lookup_field='uuid'
+ )
+
+ class Meta:
+ model = MyModel
+ 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):
+ created = models.DateTimeField()
+ to_email = models.EmailField()
+ message = models.CharField(max_length=1000)
+
+ def expiry_date(self):
+ return self.created + datetime.timedelta(days=30)
+
+You can include `expiry_date` as a field option on a `ModelSerializer` class.
+
+ class InvitationSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Invitation
+ fields = ('to_email', 'message', 'expiry_date')
+
+These fields will be mapped to `serializers.ReadOnlyField()` instances.
+
+ >>> serializer = InvitationSerializer()
+ >>> print repr(serializer)
+ InvitationSerializer():
+ to_email = EmailField(max_length=75)
+ message = CharField(max_length=1000)
+ 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):
+ 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()` - Overide either or both of these to support saving instances.
+
+##### 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):
+ created = models.DateTimeField(auto_now_add=True)
+ player_name = models.CharField(max_length=10)
+ score = models.IntegerField()
+
+It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types.
+
+ class HighScoreSerializer(serializers.BaseSerializer):
+ def to_representation(self, obj):
+ return {
+ 'score': obj.score,
+ 'player_name': obj.player_name
+ }
+
+We can now use this class to serialize single `HighScore` instances:
+
+ @api_view(['GET'])
+ def high_score(request, pk):
+ instance = HighScore.objects.get(pk=pk)
+ serializer = HighScoreSerializer(instance)
+ return Response(serializer.data)
+
+Or use it to serialize multiple instances:
+
+ @api_view(['GET'])
+ def all_high_scores(request):
+ queryset = HighScore.objects.order_by('-score')
+ serializer = HighScoreSerializer(queryset, many=True)
+ 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):
+ def to_internal_value(self, data):
+ score = data.get('score')
+ player_name = data.get('player_name')
+
+ # Perform the data validation.
+ if not score:
+ raise ValidationError({
+ 'score': 'This field is required.'
+ })
+ if not player_name:
+ raise ValidationError({
+ 'player_name': 'This field is required.'
+ })
+ if len(player_name) > 10:
+ raise ValidationError({
+ 'player_name': 'May not be more than 10 characters.'
+ })
+
+ # Return the validated values. This will be available as
+ # the `.validated_data` property.
+ return {
+ 'score': int(score),
+ 'player_name': player_name
+ }
+
+ def to_representation(self, obj):
+ return {
+ 'score': obj.score,
+ 'player_name': obj.player_name
+ }
+
+ def create(self, validated_data):
+ return HighScore.objects.create(**validated_data)
+
+#### 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 aribitrary objects into primitive representations.
+
+ class ObjectSerializer(serializers.BaseSerializer):
+ """
+ A read-only serializer that coerces arbitrary complex objects
+ into primitive representations.
+ """
+ def to_representation(self, obj):
+ for attribute_name in dir(obj):
+ attribute = getattr(obj, attribute_name)
+ if attribute_name('_'):
+ # Ignore private attributes.
+ pass
+ elif hasattr(attribute, '__call__'):
+ # Ignore methods and other callables.
+ pass
+ elif isinstance(attribute, (str, int, bool, float, type(None))):
+ # Primitive types can be passed through unmodified.
+ output[attribute_name] = attribute
+ elif isinstance(attribute, list):
+ # Recursivly deal with items in lists.
+ output[attribute_name] = [
+ self.to_representation(item) for item in attribute
+ ]
+ elif isinstance(attribute, dict):
+ # Recursivly deal with items in dictionarys.
+ output[attribute_name] = {
+ str(key): self.to_representation(value)
+ for key, value in attribute.items()
+ }
+ else:
+ # Force anything else to its string representation.
+ output[attribute_name] = str(attribute)
+
+## Serializer fields
+
+#### 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_none`, `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_none` 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=`: 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_none=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_none=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.
+
+#### 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):
+ 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):
+ """A custom read-only field that returns the class name."""
+ 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):
+ # Pass the entire object through to `to_representation()`,
+ # instead of the standard attribute lookup.
+ return obj
+
+ def to_representation(self, value):
+ return value.__class__.__name__
+
+#### 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):
+ organizations = serializers.SlugRelatedField(slug_field='name')
+
+ class Meta:
+ model = Account
+
+However this code *would not be valid* in `2.4.3`:
+
+ # Missing `queryset`
+ class AccountSerializer(serializers.Serializer):
+ organizations = serializers.SlugRelatedField(slug_field='name')
+
+ def restore_object(self, attrs, instance=None):
+ # ...
+
+The queryset argument is now always required for writable relational fields.
+This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes.
+
+ class AccountSerializer(serializers.ModelSerializer):
+ organizations = serializers.SlugRelatedField(
+ slug_field='name',
+ queryset=Organization.objects.all()
+ )
+
+ class Meta:
+ 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_`. For example the following is valid:
+
+ class AccountSerializer(serializers.Serializer):
+ # `method_name='get_billing_details'` by default.
+ billing_details = serializers.SerializerMethodField()
+
+ def get_billing_details(self, account):
+ return calculate_billing(account)
+
+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
+ from rest_framework.validators import UniqueValidator
+
+ class OrganizationSerializer(serializers.Serializer):
+ url = serializers.HyperlinkedIdentityField(view_name='organization_detail')
+ created = serializers.DateTimeField(read_only=True)
+ name = serializers.CharField(
+ max_length=100,
+ validators=UniqueValidator(queryset=Organization.objects.all())
+ )
+
+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):
+ category = serializers.ChoiceField(['5k', '10k'])
+ position = serializers.IntegerField()
+ name = serializers.CharField(max_length=100)
+
+ default_validators = [UniqueTogetherValidator(
+ queryset=RaceResult.objects.all(),
+ fields=('category', 'position')
+ )]
+
+#### 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](../api-guide/validators.md) section of the documentation.
+
+## Generic views
+
+#### 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):
+ # Include the owner attribute directly, rather than from request data.
+ instance = serializer.save(owner=self.request.user)
+ # Perform a custom post-save action.
+ send_email(instance.to_email, instance.message)
+
+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):
+ # Perform a custom pre-delete action.
+ send_deletion_alert(user=instance.created_by, deleted=instance)
+ # Delete the object instance.
+ 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](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) 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.
+
+## The metadata API
+
+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.
+
+## Serializers as HTML forms
+
+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…
+
+ additional_notes = serializers.CharField(
+ style={'base_template': 'text_area.html'}
+ )
+
+Similarly, to use a radio button control instead of the default `select` control, you would use the following…
+
+ color_channel = serializers.ChoiceField(
+ choices=['red', 'blue', 'green'],
+ style={'base_template': 'radio.html'}
+ )
+
+This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
+
+## API style
+
+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 = {
+ 'UNICODE_JSON': False
+ }
+
+#### 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 = {
+ 'COMPACT_JSON': False
+ }
+
+#### 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](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-uploaded-files-in-development).
+
+You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key:
+
+ REST_FRAMEWORK = {
+ 'UPLOADED_FILES_USE_URL': False
+ }
+
+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}
+ serializer = ExampleSerializer(instance, context=context)
+ return 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 = {
+ # Return native `Date` and `Time` objects in `serializer.data`
+ 'DATETIME_FORMAT': None
+ 'DATE_FORMAT': None
+ 'TIME_FORMAT': None
+ }
+
+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.
+ created = 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 = {
+ 'COERCE_DECIMAL_TO_STRING': False
+ }
+
+Or modify it on an individual serializer field, using the `coerce_to_string` keyword argument.
+
+ # Return `Decimal` instances in `serializer.data`, not strings.
+ amount = serializers.DecimalField(
+ max_digits=10,
+ decimal_places=2,
+ coerce_to_string=False
+ )
+
+The default JSON renderer will return float objects for uncoerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
+
+## Miscellaneous notes.
+
+* 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.
+
+## What's coming next.
+
+3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
+
+The 3.1 release is planned to address improvements in the following components:
+
+* Public API for using serializers as HTML forms.
+* Request parsing, mediatypes & the implementation of the browsable API.
+* Introduction of a new pagination API.
+* Better support for API versioning.
+
+The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
+
+You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/tomchristie/django-rest-framework/milestones).
+
+[mixins.py]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py
diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md
index 97dd4710b..ad88810da 100644
--- a/docs/topics/ajax-csrf-cors.md
+++ b/docs/topics/ajax-csrf-cors.md
@@ -10,7 +10,7 @@ If you’re building a JavaScript client to interface with your Web API, you'll
AJAX requests that are made within the same context as the API they are interacting with will typically use `SessionAuthentication`. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.
-AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`.
+AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`.
## CSRF protection
@@ -19,7 +19,7 @@ AJAX requests that are made on a different site from the API they are communicat
To guard against these type of attacks, you need to do two things:
1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` cannot be used to alter any server-side state.
-2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token.
+2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token.
If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations.
@@ -35,7 +35,7 @@ The best way to deal with CORS in REST framework is to add the required response
[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
-[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
+[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
[cors]: http://www.w3.org/TR/cors/
[ottoyiu]: https://github.com/ottoyiu/
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md
index 3400bc8f9..7654136cf 100644
--- a/docs/topics/contributing.md
+++ b/docs/topics/contributing.md
@@ -10,9 +10,9 @@ There are many ways you can contribute to Django REST framework. We'd like it t
The 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.
-If 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.
+If 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.
-Other really great ways you can help move the community forward include helping answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
+Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
@@ -33,7 +33,7 @@ Some tips on good issue reporting:
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
-* Feature 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 maintainence overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
+* Feature 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.
* Closing 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.
## Triaging issues
@@ -52,7 +52,7 @@ To start developing on Django REST framework, clone the repo:
git clone git@github.com:tomchristie/django-rest-framework.git
-Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you setup your editor to automatically indicated non-conforming styles.
+Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
## Testing
@@ -71,31 +71,31 @@ To run the tests, clone the repository, and then:
Run using a more concise output style.
- ./runtests -q
+ ./runtests.py -q
Run the tests using a more concise output style, no coverage, no flake8.
- ./runtests --fast
+ ./runtests.py --fast
Don't run the flake8 code linting.
- ./runtests --nolint
+ ./runtests.py --nolint
Only run the flake8 code linting, don't run the tests.
- ./runtests --lintonly
+ ./runtests.py --lintonly
Run the tests for a given test case.
- ./runtests MyTestCase
+ ./runtests.py MyTestCase
Run the tests for a given test method.
- ./runtests MyTestCase.test_this_method
+ ./runtests.py MyTestCase.test_this_method
Shorter form to run the tests for a given test method.
- ./runtests test_this_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.
@@ -109,7 +109,7 @@ You can also use the excellent [tox][tox] testing tool to run the tests against
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 seperate issue without interfering with an ongoing pull requests.
+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.
@@ -117,7 +117,7 @@ GitHub's documentation for working on pull requests is [available here][pull-req
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 runnning as you'd expect.
+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.
![Travis status][travis-status]
@@ -131,19 +131,19 @@ Sometimes, in order to ensure your code works on various different versions of D
The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
-There are many great markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
+There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
## Building the documentation
-To build the documentation, simply run the `mkdocs.py` script.
+To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
- ./mkdocs.py
+ mkdocs build
-This will build the html output into the `html` directory.
+This will build the documentation into the `site` directory.
-You can build the documentation and open a preview in a browser window by using the `-p` flag.
+You can build the documentation and open a preview in a browser window by using the `serve` command.
- ./mkdocs.py -p
+ mkdocs serve
## Language style
@@ -153,7 +153,7 @@ Some other tips:
* Keep paragraphs reasonably short.
* Use double spacing after the end of sentences.
-* Don't use the abbreviations such as 'e.g.' but instead use long form, such as 'For example'.
+* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
## Markdown style
@@ -186,7 +186,7 @@ If you are hyperlinking to another REST framework document, you should use a rel
[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.
+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
@@ -210,7 +210,9 @@ We recommend the [`django-reusable-app`][django-reusable-app] template as a good
## Linking to your package
-Once your package is decently documented and available on PyPI open a pull request or issue, and we'll add a link to it from the main REST framework documentation.
+Once your package is decently documented and available on PyPI open a pull request or issue, 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][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Resources][third-party-resources] section.
+
+We also suggest adding it to the [REST Framework][rest-framework-grid] grid on Django Packages.
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
[code-of-conduct]: https://www.djangoproject.com/conduct/
@@ -225,3 +227,7 @@ Once your package is decently documented and available on PyPI open a pull reque
[docs]: https://github.com/tomchristie/django-rest-framework/tree/master/docs
[mou]: http://mouapp.com/
[django-reusable-app]: https://github.com/dabapps/django-reusable-app
+[authentication]: ../api-guide/authentication.md
+[permissions]: ../api-guide/permissions.md
+[third-party-resources]: third-party-resources.md
+[rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/
diff --git a/docs/topics/documenting-your-api.md b/docs/topics/documenting-your-api.md
index e20f97122..d65e251f1 100644
--- a/docs/topics/documenting-your-api.md
+++ b/docs/topics/documenting-your-api.md
@@ -54,7 +54,7 @@ The title that is used in the browsable API is generated from the view class nam
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`.
+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
@@ -65,9 +65,9 @@ If the python `markdown` library is installed, then [markdown syntax][markdown]
class AccountListView(views.APIView):
"""
Returns a list of all **active** accounts in the system.
-
+
For more details on how accounts are activated please [see here][ref].
-
+
[ref]: http://example.com/activating-accounts
"""
@@ -84,7 +84,7 @@ You can modify the response behavior to `OPTIONS` requests by overriding the `me
def metadata(self, request):
"""
Don't include the view description in OPTIONS responses.
- """
+ """
data = super(ExampleView, self).metadata(request)
data.pop('description')
return data
diff --git a/docs/topics/kickstarter-announcement.md b/docs/topics/kickstarter-announcement.md
index 7d1f6d0eb..e8bad95be 100644
--- a/docs/topics/kickstarter-announcement.md
+++ b/docs/topics/kickstarter-announcement.md
@@ -160,4 +160,4 @@ The following individuals made a significant financial contribution to the devel
### 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!
\ No newline at end of file
+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!
diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md
index 16589f3b9..9fca949ab 100644
--- a/docs/topics/release-notes.md
+++ b/docs/topics/release-notes.md
@@ -40,6 +40,16 @@ You can determine your currently installed version using `pip freeze`:
## 2.4.x series
+### 2.4.4
+
+**Date**: [3rd November 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.4+Release%22+).
+
+* **Security fix**: Escape URLs when replacing `format=` query parameter, as used in dropdown on `GET` button in browsable API to allow explicit selection of JSON vs HTML output.
+* Maintain ordering of URLs in API root view for `DefaultRouter`.
+* Fix `follow=True` in `APIRequestFactory`
+* Resolve issue with invalid `read_only=True`, `required=True` fields being automatically generated by `ModelSerializer` in some cases.
+* Resolve issue with `OPTIONS` requests returning incorrect information for views using `get_serializer_class` to dynamically determine serializer based on request method.
+
### 2.4.3
**Date**: [19th September 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.3+Release%22+).
@@ -53,7 +63,7 @@ You can determine your currently installed version using `pip freeze`:
* Bugfix: Fix migration in `authtoken` application.
* Bugfix: Allow selection of integer keys in nested choices.
* Bugfix: Return `None` instead of `'None'` in `CharField` with `allow_none=True`.
-* Bugfix: Ensure custom model fields map to equivelent serializer fields more reliably.
+* Bugfix: Ensure custom model fields map to equivelent serializer fields more reliably.
* Bugfix: `DjangoFilterBackend` no longer quietly changes queryset ordering.
### 2.4.2
@@ -149,7 +159,7 @@ You can determine your currently installed version using `pip freeze`:
* Added `write_only_fields` option to `ModelSerializer` classes.
* JSON renderer now deals with objects that implement a dict-like interface.
* Fix compatiblity with newer versions of `django-oauth-plus`.
-* Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unneccessary queryset re-evaluations.
+* Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unnecessary queryset re-evaluations.
* Bugfix: Allow defaults on BooleanFields to be properly honored when values are not supplied.
* Bugfix: Prevent double-escaping of non-latin1 URL query params when appending `format=json` params.
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
index f1060d90b..a7746932e 100644
--- a/docs/topics/rest-framework-2-announcement.md
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -8,7 +8,7 @@ What it is, and why you should care.
---
-**Announcement:** REST framework 2 released - Tue 30th Oct 2012
+**Announcement:** REST framework 2 released - Tue 30th Oct 2012
---
@@ -37,7 +37,7 @@ REST framework 2 includes a totally re-worked serialization engine, that was ini
* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API.
* Structural concerns are decoupled from encoding concerns.
* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
-* Validation that can be mapped to obvious and comprehensive error responses.
+* Validation that can be mapped to obvious and comprehensive error responses.
* Serializers that support both nested, flat, and partially-nested representations.
* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md
index 3d7004880..4e3ccf924 100644
--- a/docs/topics/rest-hypermedia-hateoas.md
+++ b/docs/topics/rest-hypermedia-hateoas.md
@@ -13,7 +13,7 @@ The following fall into the "required reading" category.
* Roy Fielding's dissertation - [Architectural Styles and
the Design of Network-based Software Architectures][dissertation].
* Roy Fielding's "[REST APIs must be hypertext-driven][hypertext-driven]" blog post.
-* Leonard Richardson & Sam Ruby's [RESTful Web Services][restful-web-services].
+* Leonard Richardson & Mike Amundsen's [RESTful Web APIs][restful-web-apis].
* Mike Amundsen's [Building Hypermedia APIs with HTML5 and Node][building-hypermedia-apis].
* Steve Klabnik's [Designing Hypermedia APIs][designing-hypermedia-apis].
* The [Richardson Maturity Model][maturitymodel].
@@ -37,7 +37,7 @@ What REST framework doesn't do is give you is machine readable hypermedia format
[cite]: http://vimeo.com/channels/restfest/page:2
[dissertation]: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
[hypertext-driven]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
-[restful-web-services]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
+[restful-web-apis]: http://restfulwebapis.org/
[building-hypermedia-apis]: http://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578
[designing-hypermedia-apis]: http://designinghypermediaapis.com/
[restisover]: http://blog.steveklabnik.com/posts/2012-02-23-rest-is-over
diff --git a/docs/topics/third-party-resources.md b/docs/topics/third-party-resources.md
index 1ca917427..ffb490af3 100644
--- a/docs/topics/third-party-resources.md
+++ b/docs/topics/third-party-resources.md
@@ -1,91 +1,322 @@
# Third Party Resources
+## About Third Party Packages
+
+Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
+
+We **support**, **encourage** and **strongly favour** the creation of Third Party Packages to encapsulate new behaviour rather than adding additional functionality directly to Django REST Framework.
+
+We aim to make creating Third Party Packages as easy as possible, whilst keeping the **simplicity** of the core API and ensuring that **maintenance** of the main project remains under control. If a Third Party Package proves popular it is relatively easy to move it into the main project; removing features is much more problematic.
+
+If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to dicuss ideas on the [Mailing List][discussion-group].
+
+## How to create a Third Party Package
+
+### Creating your package
+
+You can use [this cookiecutter template][cookiecutter] 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
+ email (default is "you@example.com")? jappleseed@example.com
+ github_username (default is "yourname")? jappleseed
+ pypi_project_name (default is "dj-package")? djangorestframework-custom-auth
+ repo_name (default is "dj-package")? django-rest-framework-custom-auth
+ app_name (default is "djpackage")? custom_auth
+ project_short_description (default is "Your project description goes here")?
+ year (default is "2014")?
+ version (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][new-repo]. If you need help, check out the [Create A Repo][create-a-repo] article on GitHub.
+
+
+#### Adding to Travis CI
+
+We recommend using [Travis CI][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][travis-ci] with your GitHub account. Once you're signed in, go to your [profile page][travis-profile] 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][pypi-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
+ $ 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
+ You probably want to also tag the version now:
+ git tag -a {0} -m 'version 0.1.0'
+ 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][semver] 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-test.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][tox-docs] 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][drf-compat] 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][rest-framework-grid] grid on Django Packages.
+
+#### Adding to the Django REST framework docs
+
+Create a [Pull Request][drf-create-pr] or [Issue][drf-create-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][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Resources][third-party-resources] section.
+
+#### Announce on the discussion group.
+
+You can also let others know about your package through the [discussion group][discussion-group].
+
+## Existing Third Party Packages
+
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](https://www.djangopackages.com/grids/g/django-rest-framework/).
+Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
-To submit new content, [open an issue](https://github.com/tomchristie/django-rest-framework/issues/new) or [create a pull request](https://github.com/tomchristie/django-rest-framework/).
-
-## Libraries and Extensions
+To submit new content, [open an issue][drf-create-issue] or [create a pull request][drf-create-pr].
### Authentication
-* [djangorestframework-digestauth](https://github.com/juanriaza/django-rest-framework-digestauth) - Provides Digest Access Authentication support.
-* [django-oauth-toolkit](https://github.com/evonove/django-oauth-toolkit) - Provides OAuth 2.0 support.
-* [doac](https://github.com/Rediker-Software/doac) - Provides OAuth 2.0 support.
-* [djangorestframework-jwt](https://github.com/GetBlimp/django-rest-framework-jwt) - Provides JSON Web Token Authentication support.
-* [hawkrest](https://github.com/kumar303/hawkrest) - Provides Hawk HTTP Authorization.
-* [djangorestframework-httpsignature](https://github.com/etoccalino/django-rest-framework-httpsignature) - Provides an easy to use HTTP Signature Authentication mechanism.
+* [djangorestframework-digestauth][djangorestframework-digestauth] - Provides Digest Access Authentication support.
+* [django-oauth-toolkit][django-oauth-toolkit] - Provides OAuth 2.0 support.
+* [doac][doac] - Provides OAuth 2.0 support.
+* [djangorestframework-jwt][djangorestframework-jwt] - Provides JSON Web Token Authentication support.
+* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
+* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
+* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
### Permissions
-* [drf-any-permissions](https://github.com/kevin-brown/drf-any-permissions) - Provides alternative permission handling.
-* [djangorestframework-composed-permissions](https://github.com/niwibe/djangorestframework-composed-permissions) - Provides a simple way to define complex permissions.
-* [rest_condition](https://github.com/caxap/rest_condition) - Another extension for building complex permissions in a simple and convenient way.
+* [drf-any-permissions][drf-any-permissions] - Provides alternative permission handling.
+* [djangorestframework-composed-permissions][djangorestframework-composed-permissions] - Provides a simple way to define complex permissions.
+* [rest_condition][rest-condition] - Another extension for building complex permissions in a simple and convenient way.
### Serializers
-* [django-rest-framework-mongoengine](https://github.com/umutbozkurt/django-rest-framework-mongoengine) - Serializer class that supports using MongoDB as the storage layer for Django REST framework.
-* [djangorestframework-gis](https://github.com/djangonauts/django-rest-framework-gis) - Geographic add-ons
-* [djangorestframework-hstore](https://github.com/djangonauts/django-rest-framework-hstore) - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.
+* [django-rest-framework-mongoengine][django-rest-framework-mongoengine] - Serializer class that supports using MongoDB as the storage layer for Django REST framework.
+* [djangorestframework-gis][djangorestframework-gis] - Geographic add-ons
+* [djangorestframework-hstore][djangorestframework-hstore] - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.
### Serializer fields
-* [drf-compound-fields](https://github.com/estebistec/drf-compound-fields) - Provides "compound" serializer fields, such as lists of simple values.
-* [django-extra-fields](https://github.com/Hipo/drf-extra-fields) - Provides extra serializer fields.
+* [drf-compound-fields][drf-compound-fields] - Provides "compound" serializer fields, such as lists of simple values.
+* [django-extra-fields][django-extra-fields] - Provides extra serializer fields.
### Views
-* [djangorestframework-bulk](https://github.com/miki725/django-rest-framework-bulk) - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
+* [djangorestframework-bulk][djangorestframework-bulk] - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
### Routers
-* [drf-nested-routers](https://github.com/alanjds/drf-nested-routers) - Provides routers and relationship fields for working with nested resources.
-* [wq.db.rest](http://wq.io/docs/about-rest) - Provides an admin-style model registration API with reasonable default URLs and viewsets.
+* [drf-nested-routers][drf-nested-routers] - Provides routers and relationship fields for working with nested resources.
+* [wq.db.rest][wq.db.rest] - Provides an admin-style model registration API with reasonable default URLs and viewsets.
### Parsers
-* [djangorestframework-msgpack](https://github.com/juanriaza/django-rest-framework-msgpack) - Provides MessagePack renderer and parser support.
-* [djangorestframework-camel-case](https://github.com/vbabiy/djangorestframework-camel-case) - Provides camel case JSON renderers and parsers.
+* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
+* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
### Renderers
-* [djangorestframework-csv](https://github.com/mjumbewu/django-rest-framework-csv) - Provides CSV renderer support.
-* [drf_ujson](https://github.com/gizmag/drf-ujson-renderer) - Implements JSON rendering using the UJSON package.
-* [Django REST Pandas](https://github.com/wq/django-rest-pandas) - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
+* [djangorestframework-csv][djangorestframework-csv] - Provides CSV renderer support.
+* [drf_ujson][drf_ujson] - Implements JSON rendering using the UJSON package.
+* [rest-pandas][rest-pandas] - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
### Filtering
-* [djangorestframework-chain](https://github.com/philipn/django-rest-framework-chain) - Allows arbitrary chaining of both relations and lookup filters.
+* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
### Misc
-* [djangorestrelationalhyperlink](https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project) - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
-* [django-rest-swagger](https://github.com/marcgibbons/django-rest-swagger) - An API documentation generator for Swagger UI.
-* [django-rest-framework-proxy ](https://github.com/eofs/django-rest-framework-proxy) - Proxy to redirect incoming request to another API server.
-* [gaiarestframework](https://github.com/AppsFuel/gaiarestframework) - Utils for django-rest-framewok
-* [drf-extensions](https://github.com/chibisov/drf-extensions) - A collection of custom extensions
-* [ember-data-django-rest-adapter](https://github.com/toranb/ember-data-django-rest-adapter) - An ember-data adapter
+* [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
+* [django-rest-swagger][django-rest-swagger] - An API documentation generator for Swagger UI.
+* [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server.
+* [gaiarestframework][gaiarestframework] - Utils for django-rest-framewok
+* [drf-extensions][drf-extensions] - A collection of custom extensions
+* [ember-data-django-rest-adapter][ember-data-django-rest-adapter] - An ember-data adapter
-## Tutorials
+## Other Resources
-* [Beginner's Guide to the Django Rest Framework](http://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786)
-* [Getting Started with Django Rest Framework and AngularJS](http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html)
-* [End to end web app with Django-Rest-Framework & AngularJS](http://blog.mourafiq.com/post/55034504632/end-to-end-web-app-with-django-rest-framework)
-* [Start Your API - django-rest-framework part 1](https://godjango.com/41-start-your-api-django-rest-framework-part-1/)
-* [Permissions & Authentication - django-rest-framework part 2](https://godjango.com/43-permissions-authentication-django-rest-framework-part-2/)
-* [ViewSets and Routers - django-rest-framework part 3](https://godjango.com/45-viewsets-and-routers-django-rest-framework-part-3/)
-* [Django Rest Framework User Endpoint](http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/)
-* [Check credentials using Django Rest Framework](http://richardtier.com/2014/03/06/110/)
+### Tutorials
-## Videos
+* [Beginner's Guide to the Django Rest Framework][beginners-guide-to-the-django-rest-framework]
+* [Getting Started with Django Rest Framework and AngularJS][getting-started-with-django-rest-framework-and-angularjs]
+* [End to end web app with Django-Rest-Framework & AngularJS][end-to-end-web-app-with-django-rest-framework-angularjs]
+* [Start Your API - django-rest-framework part 1][start-your-api-django-rest-framework-part-1]
+* [Permissions & Authentication - django-rest-framework part 2][permissions-authentication-django-rest-framework-part-2]
+* [ViewSets and Routers - django-rest-framework part 3][viewsets-and-routers-django-rest-framework-part-3]
+* [Django Rest Framework User Endpoint][django-rest-framework-user-endpoint]
+* [Check credentials using Django Rest Framework][check-credentials-using-django-rest-framework]
-* [Ember and Django Part 1 (Video)](http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1)
-* [Django Rest Framework Part 1 (Video)](http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1)
-* [Pyowa July 2013 - Django Rest Framework (Video)](http://www.youtube.com/watch?v=E1ZrehVxpBo)
-* [django-rest-framework and angularjs (Video)](http://www.youtube.com/watch?v=Q8FRBGTJ020)
+### Videos
-## Articles
+* [Ember and Django Part 1 (Video)][ember-and-django-part 1-video]
+* [Django Rest Framework Part 1 (Video)][django-rest-framework-part-1-video]
+* [Pyowa July 2013 - Django Rest Framework (Video)][pyowa-july-2013-django-rest-framework-video]
+* [django-rest-framework and angularjs (Video)][django-rest-framework-and-angularjs-video]
-* [Web API performance: profiling Django REST framework](http://dabapps.com/blog/api-performance-profiling-django-rest-framework/)
-* [API Development with Django and Django REST Framework](https://bnotions.com/api-development-with-django-and-django-rest-framework/)
+### Articles
+
+* [Web API performance: profiling Django REST framework][web-api-performance-profiling-django-rest-framework]
+* [API Development with Django and Django REST Framework][api-development-with-django-and-django-rest-framework]
+
+
+[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
+[new-repo]: https://github.com/new
+[create-a-repo]: https://help.github.com/articles/create-a-repo/
+[travis-ci]: https://travis-ci.org
+[travis-profile]: https://travis-ci.org/profile
+[pypi-register]: https://pypi.python.org/pypi?%3Aaction=register_form
+[semver]: http://semver.org/
+[tox-docs]: https://tox.readthedocs.org/en/latest/
+[drf-compat]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/compat.py
+[rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/
+[drf-create-pr]: https://github.com/tomchristie/django-rest-framework/compare
+[drf-create-issue]: https://github.com/tomchristie/django-rest-framework/issues/new
+[authentication]: ../api-guide/authentication.md
+[permissions]: ../api-guide/permissions.md
+[discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework
+[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
+[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
+[doac]: https://github.com/Rediker-Software/doac
+[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
+[hawkrest]: https://github.com/kumar303/hawkrest
+[djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature
+[djoser]: https://github.com/sunscrapers/djoser
+[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions
+[djangorestframework-composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
+[rest-condition]: https://github.com/caxap/rest_condition
+[django-rest-framework-mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
+[djangorestframework-gis]: https://github.com/djangonauts/django-rest-framework-gis
+[djangorestframework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
+[drf-compound-fields]: https://github.com/estebistec/drf-compound-fields
+[django-extra-fields]: https://github.com/Hipo/drf-extra-fields
+[djangorestframework-bulk]: https://github.com/miki725/django-rest-framework-bulk
+[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
+[wq.db.rest]: http://wq.io/docs/about-rest
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
+[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
+[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
+[drf_ujson]: https://github.com/gizmag/drf-ujson-renderer
+[rest-pandas]: https://github.com/wq/django-rest-pandas
+[djangorestframework-chain]: https://github.com/philipn/django-rest-framework-chain
+[djangorestrelationalhyperlink]: https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project
+[django-rest-swagger]: https://github.com/marcgibbons/django-rest-swagger
+[django-rest-framework-proxy]: https://github.com/eofs/django-rest-framework-proxy
+[gaiarestframework]: https://github.com/AppsFuel/gaiarestframework
+[drf-extensions]: https://github.com/chibisov/drf-extensions
+[ember-data-django-rest-adapter]: https://github.com/toranb/ember-data-django-rest-adapter
+[beginners-guide-to-the-django-rest-framework]: http://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786
+[getting-started-with-django-rest-framework-and-angularjs]: http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html
+[end-to-end-web-app-with-django-rest-framework-angularjs]: http://blog.mourafiq.com/post/55034504632/end-to-end-web-app-with-django-rest-framework
+[start-your-api-django-rest-framework-part-1]: https://godjango.com/41-start-your-api-django-rest-framework-part-1/
+[permissions-authentication-django-rest-framework-part-2]: https://godjango.com/43-permissions-authentication-django-rest-framework-part-2/
+[viewsets-and-routers-django-rest-framework-part-3]: https://godjango.com/45-viewsets-and-routers-django-rest-framework-part-3/
+[django-rest-framework-user-endpoint]: http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
+[check-credentials-using-django-rest-framework]: http://richardtier.com/2014/03/06/110/
+[ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1
+[django-rest-framework-part-1-video]: http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1
+[pyowa-july-2013-django-rest-framework-video]: http://www.youtube.com/watch?v=e1zrehvxpbo
+[django-rest-framework-and-angularjs-video]: http://www.youtube.com/watch?v=q8frbgtj020
+[web-api-performance-profiling-django-rest-framework]: http://dabapps.com/blog/api-performance-profiling-django-rest-framework/
+[api-development-with-django-and-django-rest-framework]: https://bnotions.com/api-development-with-django-and-django-rest-framework/
diff --git a/docs/topics/writable-nested-serializers.md b/docs/topics/writable-nested-serializers.md
index 66ea78150..ed614bd24 100644
--- a/docs/topics/writable-nested-serializers.md
+++ b/docs/topics/writable-nested-serializers.md
@@ -6,9 +6,9 @@
Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.
-Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependancies between the various model instances, and the need to save or delete multiple instances in a single action.
+Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependencies between the various model instances, and the need to save or delete multiple instances in a single action.
-## One-to-many data structures
+## One-to-many data structures
*Example of a **read-only** nested serializer. Nothing complex to worry about here.*
@@ -16,10 +16,10 @@ Nested data structures are easy enough to work with if they're read-only - simpl
class Meta:
model = ToDoItem
fields = ('text', 'is_completed')
-
+
class ToDoListSerializer(serializers.ModelSerializer):
items = ToDoItemSerializer(many=True, read_only=True)
-
+
class Meta:
model = ToDoList
fields = ('title', 'items')
@@ -31,7 +31,7 @@ Some example output from our serializer.
'items': {
{'text': 'Compile playlist', 'is_completed': True},
{'text': 'Send invites', 'is_completed': False},
- {'text': 'Clean house', 'is_completed': False}
+ {'text': 'Clean house', 'is_completed': False}
}
}
@@ -44,4 +44,4 @@ Let's take a look at updating our nested one-to-many data structure.
### Making PATCH requests
-[cite]: http://jsonapi.org/format/#url-based-json-api
\ No newline at end of file
+[cite]: http://jsonapi.org/format/#url-based-json-api
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index b0565d91a..f9027b688 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -41,20 +41,7 @@ Once that's done we can create an app that we'll use to create a simple Web API.
python manage.py startapp snippets
-The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`.
-
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': 'tmp.db',
- 'USER': '',
- 'PASSWORD': '',
- 'HOST': '',
- 'PORT': '',
- }
- }
-
-We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`.
+We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file:
INSTALLED_APPS = (
...
@@ -72,7 +59,7 @@ Okay, we're ready to roll.
## Creating a model to work with
-For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` 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.
+For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` 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.
from django.db import models
from pygments.lexers import get_all_lexers
@@ -98,9 +85,10 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
class Meta:
ordering = ('created',)
-Don't forget to sync the database for the first time.
+We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
- python manage.py syncdb
+ python manage.py makemigrations snippets
+ python manage.py migrate
## Creating a Serializer class
@@ -112,42 +100,41 @@ The first thing we need to get started on our Web API is to provide a way of ser
class SnippetSerializer(serializers.Serializer):
- pk = serializers.Field() # Note: `Field` is an untyped read-only field.
+ pk = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False,
max_length=100)
- code = serializers.CharField(widget=widgets.Textarea,
- max_length=100000)
+ code = serializers.CharField(style={'type': 'textarea'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES,
default='friendly')
- def restore_object(self, attrs, instance=None):
+ def create(self, validated_attrs):
"""
- Create or update a new snippet instance, given a dictionary
- of deserialized field values.
-
- Note that if we don't define this method, then deserializing
- data will simply return a dictionary of items.
+ Create and return a new `Snippet` instance, given the validated data.
"""
- if instance:
- # Update existing instance
- instance.title = attrs.get('title', instance.title)
- instance.code = attrs.get('code', instance.code)
- instance.linenos = attrs.get('linenos', instance.linenos)
- instance.language = attrs.get('language', instance.language)
- instance.style = attrs.get('style', instance.style)
- return instance
+ return Snippet.objects.create(**validated_attrs)
- # Create new instance
- return Snippet(**attrs)
+ def update(self, instance, validated_attrs):
+ """
+ Update and return an existing `Snippet` instance, given the validated data.
+ """
+ instance.title = validated_attrs.get('title', instance.title)
+ instance.code = validated_attrs.get('code', instance.code)
+ instance.linenos = validated_attrs.get('linenos', instance.linenos)
+ instance.language = validated_attrs.get('language', instance.language)
+ instance.style = validated_attrs.get('style', instance.style)
+ instance.save()
+ return instance
-The first part of the serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
+The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()`
-Notice that we can also use various attributes that would typically be used on form fields, such as `widget=widgets.Textarea`. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
+A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`.
-We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit.
+The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `style={'type': 'textarea'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
+
+We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit.
## Working with Serializers
@@ -219,6 +206,24 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer`
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
+Once nice property that serializers have is that you can inspect all the fields an serializer instance, by printing it's representation. Open the Django shell with `python manange.py shell`, then try the following:
+
+ >>> from snippets.serializers import SnippetSerializer
+ >>> serializer = SnippetSerializer()
+ >>> print repr(serializer) # In python 3 use `print(repr(serializer))`
+ SnippetSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ title = CharField(allow_blank=True, max_length=100, required=False)
+ code = CharField(style={'type': 'textarea'})
+ linenos = BooleanField(required=False)
+ language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
+ style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
+
+It's important to remember that `ModelSerializer` classes don't do anything particularly magically, they are simply a shortcut to creating a serializer class with:
+
+* An automatically determined set of fields.
+* Simple default implementations for the `create()` and `update()` methods.
+
## Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class.
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 9120e2547..4e4edeeac 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -44,7 +44,9 @@ When that's all done we'll need to update our database tables.
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
rm tmp.db
- python manage.py syncdb
+ rm -r snippets/migrations
+ python manage.py makemigrations snippets
+ python manage.py migrate
You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
@@ -92,24 +94,26 @@ Finally we need to add those views into the API, by referencing them from the UR
Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
-The way we deal with that is by overriding a `.pre_save()` method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.
+The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.
-On **both** the `SnippetList` and `SnippetDetail` view classes, add the following method:
+On the `SnippetList` view class, add the following method:
- def pre_save(self, obj):
- obj.owner = self.request.user
+ def perform_create(self, serializer):
+ serializer.save(owner=self.request.user)
+
+The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.
## Updating our serializer
Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`:
- owner = serializers.Field(source='owner.username')
+ owner = serializers.ReadOnlyField(source='owner.username')
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
-The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
+The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here.
## Adding required permissions to views
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 36473ce91..50552616b 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -6,7 +6,6 @@ At the moment relationships within our API are represented by using primary keys
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add:
- from rest_framework import renderers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md
index cf37a2601..3fad509a1 100644
--- a/docs/tutorial/6-viewsets-and-routers.md
+++ b/docs/tutorial/6-viewsets-and-routers.md
@@ -60,7 +60,7 @@ To see what's going on under the hood let's first explicitly create a set of vie
In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views.
- from snippets.views import SnippetViewSet, UserViewSet
+ from snippets.views import SnippetViewSet, UserViewSet, api_root
from rest_framework import renderers
snippet_list = SnippetViewSet.as_view({
diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md
index 813e9872c..1c398c1ff 100644
--- a/docs/tutorial/quickstart.md
+++ b/docs/tutorial/quickstart.md
@@ -19,18 +19,20 @@ Create a new Django project named `tutorial`, then start a new app called `quick
pip install djangorestframework
# Set up a new project with a single application
- django-admin.py startproject tutorial .
+ django-admin.py startproject tutorial
cd tutorial
django-admin.py startapp quickstart
cd ..
Now sync your database for the first time:
- python manage.py syncdb
+ python manage.py migrate
-Make sure to create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example.
+We'll also create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example.
-Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding...
+ python manage.py createsuperuser
+
+Once 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...
## Serializers
diff --git a/docs/404.html b/docs_theme/404.html
similarity index 60%
rename from docs/404.html
rename to docs_theme/404.html
index 864247e78..44993e37d 100644
--- a/docs/404.html
+++ b/docs_theme/404.html
@@ -1,50 +1,54 @@
-
-
- Django REST framework - 404 - Page not found
-
-
-
-
-
-
-
-
-
-
+
+
+
+ Django REST framework - 404 - Page not found
+
+
+
+
+
-
-
+
+
+
+
+
-
+
- var _gaq = _gaq || [];
- _gaq.push(['_setAccount', 'UA-18852272-2']);
- _gaq.push(['_trackPageview']);
+
+
-
-
-
+