Merge branch 'master' into set-retry-after
Conflicts: tests/test_throttling.py
35
.travis.yml
|
@ -5,40 +5,39 @@ python:
|
|||
- "2.7"
|
||||
- "3.2"
|
||||
- "3.3"
|
||||
- "3.4"
|
||||
|
||||
env:
|
||||
- DJANGO="https://www.djangoproject.com/download/1.7b1/tarball/"
|
||||
- DJANGO="django==1.6.2"
|
||||
- DJANGO="django==1.5.5"
|
||||
- DJANGO="django==1.4.10"
|
||||
- DJANGO="django==1.3.7"
|
||||
- DJANGO="https://www.djangoproject.com/download/1.7c2/tarball/"
|
||||
- DJANGO="django==1.6.5"
|
||||
- DJANGO="django==1.5.8"
|
||||
- DJANGO="django==1.4.13"
|
||||
|
||||
install:
|
||||
- pip install $DJANGO
|
||||
- pip install defusedxml==0.3 Pillow==2.3.0
|
||||
- pip install defusedxml==0.3
|
||||
- pip install Pillow==2.3.0
|
||||
- pip install django-guardian==1.2.3
|
||||
- pip install pytest-django==2.6.1
|
||||
- pip install flake8==2.2.2
|
||||
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install oauth2==1.5.211; fi"
|
||||
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth-plus==2.2.4; fi"
|
||||
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth2-provider==0.2.4; fi"
|
||||
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-guardian==1.1.1; fi"
|
||||
- "if [[ ${DJANGO::11} == 'django==1.3' ]]; then pip install django-filter==0.5.4; fi"
|
||||
- "if [[ ${DJANGO::11} != 'django==1.3' ]]; then pip install django-filter==0.7; fi"
|
||||
- "if [[ ${TRAVIS_PYTHON_VERSION::1} == '3' ]]; then pip install -e git+https://github.com/linovia/django-guardian.git@feature/django_1_7#egg=django-guardian-1.2.0; fi"
|
||||
- "if [[ ${DJANGO} == 'https://www.djangoproject.com/download/1.7b1/tarball/' ]]; then pip install -e git+https://github.com/linovia/django-guardian.git@feature/django_1_7#egg=django-guardian-1.2.0; fi"
|
||||
- "if [[ ${DJANGO} == 'https://www.djangoproject.com/download/1.7c2/tarball/' ]]; then pip install -e git+https://github.com/linovia/django-guardian.git@feature/django_1_7#egg=django-guardian-1.2.0; fi"
|
||||
- export PYTHONPATH=.
|
||||
|
||||
script:
|
||||
- python rest_framework/runtests/runtests.py
|
||||
- ./runtests.py
|
||||
|
||||
matrix:
|
||||
exclude:
|
||||
- python: "2.6"
|
||||
env: DJANGO="https://www.djangoproject.com/download/1.7b1/tarball/"
|
||||
env: DJANGO="https://www.djangoproject.com/download/1.7c2/tarball/"
|
||||
- python: "3.2"
|
||||
env: DJANGO="django==1.4.10"
|
||||
- python: "3.2"
|
||||
env: DJANGO="django==1.3.7"
|
||||
env: DJANGO="django==1.4.13"
|
||||
- python: "3.3"
|
||||
env: DJANGO="django==1.4.10"
|
||||
- python: "3.3"
|
||||
env: DJANGO="django==1.3.7"
|
||||
|
||||
env: DJANGO="django==1.4.13"
|
||||
- python: "3.4"
|
||||
env: DJANGO="django==1.4.13"
|
||||
|
|
|
@ -65,7 +65,7 @@ To run the tests, clone the repository, and then:
|
|||
pip install -r optionals.txt
|
||||
|
||||
# Run the tests
|
||||
rest_framework/runtests/runtests.py
|
||||
py.test
|
||||
|
||||
You can also use the excellent [`tox`][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
# Overview
|
||||
|
||||
Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
|
||||
Django REST framework is a powerful and flexible toolkit for building Web APIs.
|
||||
|
||||
Some reasons you might want to use REST framework:
|
||||
|
||||
|
@ -27,7 +27,7 @@ There is a live example API for testing purposes, [available here][sandbox].
|
|||
# Requirements
|
||||
|
||||
* Python (2.6.5+, 2.7, 3.2, 3.3)
|
||||
* Django (1.3, 1.4, 1.5, 1.6)
|
||||
* Django (1.4.2+, 1.5, 1.6, 1.7)
|
||||
|
||||
# Installation
|
||||
|
||||
|
@ -136,6 +136,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
[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
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
|
|
|
@ -119,14 +119,20 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
|
|||
|
||||
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
|
||||
|
||||
To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
|
||||
To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
|
||||
|
||||
INSTALLED_APPS = (
|
||||
...
|
||||
'rest_framework.authtoken'
|
||||
)
|
||||
|
||||
Make sure to run `manage.py syncdb` after changing your settings. The `authtoken` database tables are managed by south (see [Schema migrations](#schema-migrations) below).
|
||||
|
||||
---
|
||||
|
||||
**Note:** Make sure to run `manage.py syncdb` after changing your settings. The `rest_framework.authtoken` app provides both Django (from v1.7) and South database migrations. See [Schema migrations](#schema-migrations) below.
|
||||
|
||||
---
|
||||
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
|
@ -198,7 +204,14 @@ Note that the default `obtain_auth_token` view explicitly uses JSON requests and
|
|||
|
||||
#### Schema migrations
|
||||
|
||||
The `rest_framework.authtoken` app includes a south migration that will create the authtoken table.
|
||||
The `rest_framework.authtoken` app includes both Django native migrations (for Django versions >1.7) and South migrations (for Django versions <1.7) that will create the authtoken table.
|
||||
|
||||
----
|
||||
|
||||
**Note**: From REST Framework v2.4.0 using South with Django <1.7 requires upgrading South v1.0+
|
||||
|
||||
----
|
||||
|
||||
|
||||
If you're using a [custom user model][custom-user-model] you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.
|
||||
|
||||
|
|
|
@ -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.
|
||||
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`
|
||||
|
||||
|
@ -164,11 +164,12 @@ Corresponds to `django.db.models.fields.BooleanField`.
|
|||
## CharField
|
||||
|
||||
A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`.
|
||||
If `allow_none` is `False` (default), `None` values will be converted to an empty string.
|
||||
|
||||
Corresponds to `django.db.models.fields.CharField`
|
||||
or `django.db.models.fields.TextField`.
|
||||
|
||||
**Signature:** `CharField(max_length=None, min_length=None)`
|
||||
**Signature:** `CharField(max_length=None, min_length=None, allow_none=False)`
|
||||
|
||||
## URLField
|
||||
|
||||
|
@ -184,7 +185,9 @@ Corresponds to `django.db.models.fields.SlugField`.
|
|||
|
||||
## ChoiceField
|
||||
|
||||
A field that can accept a value out of a limited set of choices.
|
||||
A field that can accept a value out of a limited set of choices. Optionally takes a `blank_display_value` parameter that customizes the display value of an empty choice.
|
||||
|
||||
**Signature:** `ChoiceField(choices=(), blank_display_value=None)`
|
||||
|
||||
## EmailField
|
||||
|
||||
|
@ -345,7 +348,7 @@ As an example, let's create a field that can be used represent the class name of
|
|||
"""
|
||||
Serialize the object's class name.
|
||||
"""
|
||||
return obj.__class__
|
||||
return obj.__class__.__name__
|
||||
|
||||
# Third party packages
|
||||
|
||||
|
@ -355,9 +358,21 @@ The following third party packages are also available.
|
|||
|
||||
The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.
|
||||
|
||||
## DRF Extra Fields
|
||||
|
||||
The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes.
|
||||
|
||||
## django-rest-framework-gis
|
||||
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
|
||||
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
|
||||
[ecma262]: http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
|
||||
[strftime]: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
|
||||
[django-widgets]: https://docs.djangoproject.com/en/dev/ref/forms/widgets/
|
||||
[iso8601]: http://www.w3.org/TR/NOTE-datetime
|
||||
[drf-compound-fields]: http://drf-compound-fields.readthedocs.org
|
||||
[drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
|
||||
[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
|
||||
|
|
|
@ -24,7 +24,7 @@ For example:
|
|||
from myapp.serializers import PurchaseSerializer
|
||||
from rest_framework import generics
|
||||
|
||||
class PurchaseList(generics.ListAPIView)
|
||||
class PurchaseList(generics.ListAPIView):
|
||||
serializer_class = PurchaseSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
|
@ -46,7 +46,7 @@ For example if your URL config contained an entry like this:
|
|||
|
||||
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
|
||||
|
||||
class PurchaseList(generics.ListAPIView)
|
||||
class PurchaseList(generics.ListAPIView):
|
||||
serializer_class = PurchaseSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
|
@ -63,7 +63,7 @@ A final example of filtering the initial queryset would be to determine the init
|
|||
|
||||
We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL:
|
||||
|
||||
class PurchaseList(generics.ListAPIView)
|
||||
class PurchaseList(generics.ListAPIView):
|
||||
serializer_class = PurchaseSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
|
@ -199,8 +199,7 @@ This enables us to make queries like:
|
|||
|
||||
http://example.com/api/products?manufacturer__name=foo
|
||||
|
||||
This is nice, but it shows underlying model structure in REST API, which may
|
||||
be undesired, but you can use:
|
||||
This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the `FilterSet` class:
|
||||
|
||||
import django_filters
|
||||
from myapp.models import Product
|
||||
|
@ -208,7 +207,6 @@ be undesired, but you can use:
|
|||
from rest_framework import generics
|
||||
|
||||
class ProductFilter(django_filters.FilterSet):
|
||||
|
||||
manufacturer = django_filters.CharFilter(name="manufacturer__name")
|
||||
|
||||
class Meta:
|
||||
|
|
|
@ -43,6 +43,12 @@ For more complex cases you might also want to override various methods on the vi
|
|||
return 20
|
||||
return 100
|
||||
|
||||
def list(self, request):
|
||||
# Note the use of `get_queryset()` instead of `self.queryset`
|
||||
queryset = self.get_queryset()
|
||||
serializer = UserSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry.
|
||||
|
||||
url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
|
||||
|
@ -63,14 +69,14 @@ Each of the concrete generic views provided is built by combining `GenericAPIVie
|
|||
|
||||
The following attributes control the basic view behavior.
|
||||
|
||||
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method.
|
||||
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
|
||||
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
|
||||
* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
|
||||
|
||||
**Shortcuts**:
|
||||
|
||||
* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. Note that `model` is only ever used for generating a default queryset or serializer class - the `queryset` and `serializer_class` attributes are always preferred if provided.
|
||||
* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. Note that `model` is only ever used for generating a default queryset or serializer class - the `queryset` and `serializer_class` attributes are always preferred if provided.
|
||||
|
||||
**Pagination**:
|
||||
|
||||
|
@ -93,6 +99,8 @@ The following attributes are used to control pagination when used with list view
|
|||
|
||||
Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute, or the default queryset for the model if the `model` shortcut is being used.
|
||||
|
||||
This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests.
|
||||
|
||||
May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request.
|
||||
|
||||
For example:
|
||||
|
@ -187,7 +195,7 @@ Remember that the `pre_save()` method is not called by `GenericAPIView` itself,
|
|||
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
|
||||
|
||||
* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys.
|
||||
* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance.
|
||||
* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False, allow_add_remove=False)` - Returns a serializer instance.
|
||||
* `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data.
|
||||
* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
|
||||
* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
|
||||
|
|
|
@ -103,6 +103,7 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie
|
|||
max_paginate_by = 100
|
||||
|
||||
Note that using a `paginate_by` value of `None` will turn off pagination for the view.
|
||||
Note if you use the `PAGINATE_BY_PARAM` settings, you also have to set the `paginate_by_param` attribute in your view to `None` in order to turn off pagination for those requests that contain the `paginate_by_param` parameter.
|
||||
|
||||
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
|
||||
|
||||
|
|
|
@ -36,6 +36,12 @@ For example:
|
|||
self.check_object_permissions(self.request, obj)
|
||||
return obj
|
||||
|
||||
#### Limitations of object level permissions
|
||||
|
||||
For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.
|
||||
|
||||
Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view.
|
||||
|
||||
## Setting the permission policy
|
||||
|
||||
The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example.
|
||||
|
@ -56,7 +62,7 @@ You can also set the authentication policy on a per-view, or per-viewset basis,
|
|||
using the `APIView` class based views.
|
||||
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.responses import Response
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
|
@ -237,7 +243,8 @@ The [REST Condition][rest-condition] package is another extension for building c
|
|||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||
[authentication]: authentication.md
|
||||
[throttling]: throttling.md
|
||||
[contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions
|
||||
[filtering]: filtering.md
|
||||
[contribauth]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-permissions
|
||||
[objectpermissions]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#handling-object-permissions
|
||||
[guardian]: https://github.com/lukaszb/django-guardian
|
||||
[get_objects_for_user]: http://pythonhosted.org/django-guardian/api/guardian.shortcuts.html#get-objects-for-user
|
||||
|
|
|
@ -138,6 +138,26 @@ Renders the request data into `YAML`.
|
|||
|
||||
Requires the `pyyaml` package to be installed.
|
||||
|
||||
Note that non-ascii characters will be rendered using `\uXXXX` character escape. For example:
|
||||
|
||||
unicode black star: "\u2605"
|
||||
|
||||
**.media_type**: `application/yaml`
|
||||
|
||||
**.format**: `'.yaml'`
|
||||
|
||||
**.charset**: `utf-8`
|
||||
|
||||
## UnicodeYAMLRenderer
|
||||
|
||||
Renders the request data into `YAML`.
|
||||
|
||||
Requires the `pyyaml` package to be installed.
|
||||
|
||||
Note that non-ascii characters will not be character escaped. For example:
|
||||
|
||||
unicode black star: ★
|
||||
|
||||
**.media_type**: `application/yaml`
|
||||
|
||||
**.format**: `'.yaml'`
|
||||
|
|
|
@ -51,36 +51,41 @@ This means you'll need to explicitly set the `base_name` argument when registeri
|
|||
|
||||
### Extra link and actions
|
||||
|
||||
Any methods on the viewset decorated with `@link` or `@action` will also be routed.
|
||||
Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed.
|
||||
For example, given a method like this on the `UserViewSet` class:
|
||||
|
||||
from myapp.permissions import IsAdminOrIsSelf
|
||||
from rest_framework.decorators import action
|
||||
from myapp.permissions import IsAdminOrIsSelf
|
||||
from rest_framework.decorators import detail_route
|
||||
|
||||
@action(permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
class UserViewSet(ModelViewSet):
|
||||
...
|
||||
|
||||
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The following URL pattern would additionally be generated:
|
||||
|
||||
* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'`
|
||||
|
||||
For more information see the viewset documentation on [marking extra actions for routing][route-decorators].
|
||||
|
||||
# API Guide
|
||||
|
||||
## SimpleRouter
|
||||
|
||||
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@link` or `@action` decorators.
|
||||
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@detail_route` or `@list_route` decorators.
|
||||
|
||||
<table border=1>
|
||||
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
||||
<tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
||||
<tr><td>POST</td><td>create</td></tr>
|
||||
<tr><td>{prefix}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</td></tr>
|
||||
<tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
||||
<tr><td>PUT</td><td>update</td></tr>
|
||||
<tr><td>PATCH</td><td>partial_update</td></tr>
|
||||
<tr><td>DELETE</td><td>destroy</td></tr>
|
||||
<tr><td rowspan=2>{prefix}/{lookup}/{methodname}/</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
|
||||
<tr><td>POST</td><td>@action decorated method</td></tr>
|
||||
<tr><td>{prefix}/{lookup}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
|
||||
</table>
|
||||
|
||||
By default the URLs created by `SimpleRouter` are appended with a trailing slash.
|
||||
|
@ -90,6 +95,12 @@ This behavior can be modified by setting the `trailing_slash` argument to `False
|
|||
|
||||
Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
|
||||
|
||||
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
|
||||
|
||||
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_id'
|
||||
lookup_value_regex = '[0-9a-f]{32}'
|
||||
|
||||
## DefaultRouter
|
||||
|
||||
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
|
||||
|
@ -99,12 +110,12 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d
|
|||
<tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
|
||||
<tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
|
||||
<tr><td>POST</td><td>create</td></tr>
|
||||
<tr><td>{prefix}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@list_route` decorated method</td><td>{basename}-{methodname}</td></tr>
|
||||
<tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
|
||||
<tr><td>PUT</td><td>update</td></tr>
|
||||
<tr><td>PATCH</td><td>partial_update</td></tr>
|
||||
<tr><td>DELETE</td><td>destroy</td></tr>
|
||||
<tr><td rowspan=2>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
|
||||
<tr><td>POST</td><td>@action decorated method</td></tr>
|
||||
<tr><td>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
|
||||
</table>
|
||||
|
||||
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
|
||||
|
@ -133,28 +144,87 @@ The arguments to the `Route` named tuple are:
|
|||
|
||||
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `suffix` argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.
|
||||
|
||||
## Customizing dynamic routes
|
||||
|
||||
You can also customize how the `@list_route` and `@detail_route` decorators are routed.
|
||||
To route either or both of these decorators, include a `DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes` list.
|
||||
|
||||
The arguments to `DynamicListRoute` and `DynamicDetailRoute` are:
|
||||
|
||||
**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{methodname}` and `{methodnamehyphen}` format strings.
|
||||
|
||||
**name**: The name of the URL as used in `reverse` calls. May include the following format strings: `{basename}`, `{methodname}` and `{methodnamehyphen}`.
|
||||
|
||||
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view.
|
||||
|
||||
## Example
|
||||
|
||||
The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention.
|
||||
|
||||
from rest_framework.routers import Route, SimpleRouter
|
||||
from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter
|
||||
|
||||
class ReadOnlyRouter(SimpleRouter):
|
||||
class CustomReadOnlyRouter(SimpleRouter):
|
||||
"""
|
||||
A router for read-only APIs, which doesn't use trailing slashes.
|
||||
"""
|
||||
routes = [
|
||||
Route(url=r'^{prefix}$',
|
||||
mapping={'get': 'list'},
|
||||
name='{basename}-list',
|
||||
initkwargs={'suffix': 'List'}),
|
||||
Route(url=r'^{prefix}/{lookup}$',
|
||||
mapping={'get': 'retrieve'},
|
||||
name='{basename}-detail',
|
||||
initkwargs={'suffix': 'Detail'})
|
||||
Route(
|
||||
url=r'^{prefix}$',
|
||||
mapping={'get': 'list'},
|
||||
name='{basename}-list',
|
||||
initkwargs={'suffix': 'List'}
|
||||
),
|
||||
Route(
|
||||
url=r'^{prefix}/{lookup}$',
|
||||
mapping={'get': 'retrieve'},
|
||||
name='{basename}-detail',
|
||||
initkwargs={'suffix': 'Detail'}
|
||||
),
|
||||
DynamicDetailRoute(
|
||||
url=r'^{prefix}/{lookup}/{methodnamehyphen}$',
|
||||
name='{basename}-{methodnamehyphen}',
|
||||
initkwargs={}
|
||||
)
|
||||
]
|
||||
|
||||
The `SimpleRouter` class provides another example of setting the `.routes` attribute.
|
||||
Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a simple viewset.
|
||||
|
||||
`views.py`:
|
||||
|
||||
class UserViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
"""
|
||||
A viewset that provides the standard actions
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
lookup_field = 'username'
|
||||
|
||||
@detail_route()
|
||||
def group_names(self, request):
|
||||
"""
|
||||
Returns a list of all the group names that the given
|
||||
user belongs to.
|
||||
"""
|
||||
user = self.get_object()
|
||||
groups = user.groups.all()
|
||||
return Response([group.name for group in groups])
|
||||
|
||||
`urls.py`:
|
||||
|
||||
router = CustomReadOnlyRouter()
|
||||
router.register('users', UserViewSet)
|
||||
urlpatterns = router.urls
|
||||
|
||||
The following mappings would be generated...
|
||||
|
||||
<table border=1>
|
||||
<tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
|
||||
<tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr>
|
||||
<tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr>
|
||||
<tr><td>/users/{username}/group-names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
|
||||
</table>
|
||||
|
||||
For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class.
|
||||
|
||||
## Advanced custom routers
|
||||
|
||||
|
@ -179,7 +249,17 @@ The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (an
|
|||
|
||||
app.router.register_model(MyModel)
|
||||
|
||||
## DRF-extensions
|
||||
|
||||
The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names].
|
||||
|
||||
[cite]: http://guides.rubyonrails.org/routing.html
|
||||
[route-decorators]: viewsets.html#marking-extra-actions-for-routing
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[wq.db]: http://wq.io/wq.db
|
||||
[wq.db-router]: http://wq.io/docs/app.py
|
||||
[drf-extensions]: http://chibisov.github.io/drf-extensions/docs/
|
||||
[drf-extensions-routers]: http://chibisov.github.io/drf-extensions/docs/#routers
|
||||
[drf-extensions-nested-viewsets]: http://chibisov.github.io/drf-extensions/docs/#nested-routes
|
||||
[drf-extensions-collection-level-controllers]: http://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
|
||||
[drf-extensions-customizable-endpoint-names]: http://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
|
||||
|
|
|
@ -73,8 +73,8 @@ Sometimes when serializing objects, you may not want to represent everything exa
|
|||
|
||||
If you need to customize the serialized value of a particular field, you can do this by creating a `transform_<fieldname>` method. For example if you needed to render some markdown from a text field:
|
||||
|
||||
description = serializers.TextField()
|
||||
description_html = serializers.TextField(source='description', read_only=True)
|
||||
description = serializers.CharField()
|
||||
description_html = serializers.CharField(source='description', read_only=True)
|
||||
|
||||
def transform_description_html(self, obj, value):
|
||||
from django.contrib.markup.templatetags.markup import markdown
|
||||
|
@ -464,7 +464,7 @@ For more specific requirements such as specifying a different lookup for each fi
|
|||
model = Account
|
||||
fields = ('url', 'account_name', 'users', 'created')
|
||||
|
||||
## Overiding the URL field behavior
|
||||
## Overriding the URL field behavior
|
||||
|
||||
The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting.
|
||||
|
||||
|
@ -478,7 +478,7 @@ You can also override this on a per-serializer basis by using the `url_field_nam
|
|||
|
||||
**Note**: The generic view implementations normally generate a `Location` header in response to successful `POST` requests. Serializers using `url_field_name` option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's `get_success_headers()` method.
|
||||
|
||||
You can also overide the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so:
|
||||
You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so:
|
||||
|
||||
class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
|
@ -580,7 +580,21 @@ The following custom model serializer could be used as a base class for model se
|
|||
def get_pk_field(self, model_field):
|
||||
return None
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
|
||||
## MongoengineModelSerializer
|
||||
|
||||
The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEngineModelSerializer` serializer class that supports using MongoDB as the storage layer for Django REST framework.
|
||||
|
||||
## GeoFeatureModelSerializer
|
||||
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides a `GeoFeatureModelSerializer` serializer class that supports GeoJSON both for read and write operations.
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
||||
[relations]: relations.md
|
||||
[mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
|
||||
[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
|
||||
|
|
|
@ -377,5 +377,11 @@ The name of a parameter in the URL conf that may be used to provide a format suf
|
|||
|
||||
Default: `'format'`
|
||||
|
||||
#### NUM_PROXIES
|
||||
|
||||
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes.
|
||||
|
||||
Default: `None`
|
||||
|
||||
[cite]: http://www.python.org/dev/peps/pep-0020/
|
||||
[strftime]: http://docs.python.org/2/library/time.html#time.strftime
|
||||
|
|
|
@ -58,7 +58,7 @@ using the `APIView` class based views.
|
|||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view('GET')
|
||||
@api_view(['GET'])
|
||||
@throttle_classes([UserRateThrottle])
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
|
@ -66,6 +66,16 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
## How clients are identified
|
||||
|
||||
The `X-Forwarded-For` and `Remote-Addr` HTTP headers are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `Remote-Addr` header will be used.
|
||||
|
||||
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `Remote-Addr` header will always be used as the identifying IP address.
|
||||
|
||||
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].
|
||||
|
||||
## Setting up the cache
|
||||
|
||||
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details.
|
||||
|
@ -178,5 +188,6 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
|
|||
|
||||
[cite]: https://dev.twitter.com/docs/error-codes-responses
|
||||
[permissions]: permissions.md
|
||||
[identifing-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
|
||||
[cache-setting]: https://docs.djangoproject.com/en/dev/ref/settings/#caches
|
||||
[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache
|
||||
|
|
|
@ -70,7 +70,7 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla
|
|||
|
||||
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
|
||||
|
||||
## Marking extra methods for routing
|
||||
## Marking extra actions for routing
|
||||
|
||||
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
|
||||
|
||||
|
@ -101,14 +101,16 @@ The default routers included with REST framework will provide routes for a stand
|
|||
def destroy(self, request, pk=None):
|
||||
pass
|
||||
|
||||
If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link` or `@action` decorators. The `@link` decorator will route `GET` requests, and the `@action` decorator will route `POST` requests.
|
||||
If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators.
|
||||
|
||||
The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects.
|
||||
|
||||
For example:
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import detail_route, list_route
|
||||
from rest_framework.response import Response
|
||||
from myapp.serializers import UserSerializer, PasswordSerializer
|
||||
|
||||
|
@ -119,7 +121,7 @@ For example:
|
|||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
|
||||
@action()
|
||||
@detail_route(methods=['post'])
|
||||
def set_password(self, request, pk=None):
|
||||
user = self.get_object()
|
||||
serializer = PasswordSerializer(data=request.DATA)
|
||||
|
@ -131,21 +133,27 @@ For example:
|
|||
return Response(serializer.errors,
|
||||
status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
The `@action` and `@link` decorators can additionally take extra arguments that will be set for the routed view only. For example...
|
||||
@list_route()
|
||||
def recent_users(self, request):
|
||||
recent_users = User.objects.all().order('-last_login')
|
||||
page = self.paginate_queryset(recent_users)
|
||||
serializer = self.get_pagination_serializer(page)
|
||||
return Response(serializer.data)
|
||||
|
||||
@action(permission_classes=[IsAdminOrIsSelf])
|
||||
The decorators can additionally take extra arguments that will be set for the routed view only. For example...
|
||||
|
||||
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
|
||||
def set_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The `@action` decorator will route `POST` requests by default, but may also accept other HTTP methods, by using the `method` argument. For example:
|
||||
Theses decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example:
|
||||
|
||||
@action(methods=['POST', 'DELETE'])
|
||||
@detail_route(methods=['post', 'delete'])
|
||||
def unset_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$`
|
||||
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
|
|
@ -307,3 +307,76 @@ table {
|
|||
.side-nav {
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
|
||||
ul.sponsor.diamond li a {
|
||||
float: left;
|
||||
width: 600px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 70px;
|
||||
padding: 300px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 600px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 200%;
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
ul.sponsor.diamond li a {
|
||||
float: left;
|
||||
width: 300px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 40px;
|
||||
padding: 300px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 280px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 150%;
|
||||
}
|
||||
}
|
||||
|
||||
ul.sponsor.platinum li a {
|
||||
float: left;
|
||||
width: 300px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 40px;
|
||||
padding: 300px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 280px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 150%;
|
||||
}
|
||||
|
||||
ul.sponsor.gold li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
}
|
||||
|
||||
ul.sponsor.silver li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
}
|
||||
|
||||
ul.sponsor {
|
||||
list-style: none;
|
||||
display: block;
|
||||
}
|
||||
|
|
BIN
docs/img/1-kuwaitnet.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
docs/img/labels-and-milestones.png
Normal file
After Width: | Height: | Size: 82 KiB |
BIN
docs/img/sponsors/0-eventbrite.png
Normal file
After Width: | Height: | Size: 22 KiB |
BIN
docs/img/sponsors/1-cyan.png
Normal file
After Width: | Height: | Size: 6.0 KiB |
BIN
docs/img/sponsors/1-divio.png
Normal file
After Width: | Height: | Size: 4.8 KiB |
BIN
docs/img/sponsors/1-kuwaitnet.png
Normal file
After Width: | Height: | Size: 3.6 KiB |
BIN
docs/img/sponsors/1-lulu.png
Normal file
After Width: | Height: | Size: 18 KiB |
BIN
docs/img/sponsors/1-potato.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
docs/img/sponsors/1-purplebit.png
Normal file
After Width: | Height: | Size: 8.9 KiB |
BIN
docs/img/sponsors/1-runscope.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
docs/img/sponsors/1-simple-energy.png
Normal file
After Width: | Height: | Size: 53 KiB |
BIN
docs/img/sponsors/1-vokal_interactive.png
Normal file
After Width: | Height: | Size: 22 KiB |
BIN
docs/img/sponsors/1-wiredrive.png
Normal file
After Width: | Height: | Size: 7.9 KiB |
BIN
docs/img/sponsors/2-byte.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
docs/img/sponsors/2-compile.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
docs/img/sponsors/2-crate.png
Normal file
After Width: | Height: | Size: 8.1 KiB |
BIN
docs/img/sponsors/2-cryptico.png
Normal file
After Width: | Height: | Size: 9.7 KiB |
BIN
docs/img/sponsors/2-django.png
Normal file
After Width: | Height: | Size: 4.9 KiB |
BIN
docs/img/sponsors/2-galileo_press.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
docs/img/sponsors/2-heroku.png
Normal file
After Width: | Height: | Size: 7.2 KiB |
BIN
docs/img/sponsors/2-hipflask.png
Normal file
After Width: | Height: | Size: 5.9 KiB |
BIN
docs/img/sponsors/2-hipo.png
Normal file
After Width: | Height: | Size: 7.9 KiB |
BIN
docs/img/sponsors/2-koordinates.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
docs/img/sponsors/2-laterpay.png
Normal file
After Width: | Height: | Size: 2.0 KiB |
BIN
docs/img/sponsors/2-lightning_kite.png
Normal file
After Width: | Height: | Size: 6.6 KiB |
BIN
docs/img/sponsors/2-mirus_research.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
docs/img/sponsors/2-nexthub.png
Normal file
After Width: | Height: | Size: 2.5 KiB |
BIN
docs/img/sponsors/2-opbeat.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
docs/img/sponsors/2-prorenata.png
Normal file
After Width: | Height: | Size: 4.0 KiB |
BIN
docs/img/sponsors/2-pulsecode.png
Normal file
After Width: | Height: | Size: 2.3 KiB |
BIN
docs/img/sponsors/2-rapasso.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
docs/img/sponsors/2-schuberg_philis.png
Normal file
After Width: | Height: | Size: 21 KiB |
BIN
docs/img/sponsors/2-security_compass.png
Normal file
After Width: | Height: | Size: 4.0 KiB |
BIN
docs/img/sponsors/2-sga.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
docs/img/sponsors/2-singing-horse.png
Normal file
After Width: | Height: | Size: 20 KiB |
BIN
docs/img/sponsors/2-sirono.png
Normal file
After Width: | Height: | Size: 4.8 KiB |
BIN
docs/img/sponsors/2-vinta.png
Normal file
After Width: | Height: | Size: 6.7 KiB |
BIN
docs/img/sponsors/3-aba.png
Normal file
After Width: | Height: | Size: 18 KiB |
BIN
docs/img/sponsors/3-aditium.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
docs/img/sponsors/3-alwaysdata.png
Normal file
After Width: | Height: | Size: 9.1 KiB |
BIN
docs/img/sponsors/3-ax_semantics.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
docs/img/sponsors/3-beefarm.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
docs/img/sponsors/3-blimp.png
Normal file
After Width: | Height: | Size: 6.1 KiB |
BIN
docs/img/sponsors/3-brightloop.png
Normal file
After Width: | Height: | Size: 6.7 KiB |
BIN
docs/img/sponsors/3-cantemo.gif
Normal file
After Width: | Height: | Size: 4.4 KiB |
BIN
docs/img/sponsors/3-crosswordtracker.png
Normal file
After Width: | Height: | Size: 6.6 KiB |
BIN
docs/img/sponsors/3-fluxility.png
Normal file
After Width: | Height: | Size: 9.8 KiB |
BIN
docs/img/sponsors/3-garfo.png
Normal file
After Width: | Height: | Size: 3.2 KiB |
BIN
docs/img/sponsors/3-gizmag.png
Normal file
After Width: | Height: | Size: 5.2 KiB |
BIN
docs/img/sponsors/3-holvi.png
Normal file
After Width: | Height: | Size: 7.4 KiB |
BIN
docs/img/sponsors/3-imt_computer_services.png
Normal file
After Width: | Height: | Size: 69 KiB |
BIN
docs/img/sponsors/3-infinite_code.png
Normal file
After Width: | Height: | Size: 21 KiB |
BIN
docs/img/sponsors/3-ipushpull.png
Normal file
After Width: | Height: | Size: 9.9 KiB |
BIN
docs/img/sponsors/3-isl.png
Normal file
After Width: | Height: | Size: 19 KiB |
BIN
docs/img/sponsors/3-life_the_game.png
Normal file
After Width: | Height: | Size: 5.4 KiB |
BIN
docs/img/sponsors/3-makespace.png
Normal file
After Width: | Height: | Size: 8.2 KiB |
BIN
docs/img/sponsors/3-nephila.png
Normal file
After Width: | Height: | Size: 8.2 KiB |
BIN
docs/img/sponsors/3-openeye.png
Normal file
After Width: | Height: | Size: 14 KiB |
BIN
docs/img/sponsors/3-pathwright.png
Normal file
After Width: | Height: | Size: 13 KiB |
BIN
docs/img/sponsors/3-phurba.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
docs/img/sponsors/3-pkgfarm.png
Normal file
After Width: | Height: | Size: 2.2 KiB |
BIN
docs/img/sponsors/3-providenz.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
docs/img/sponsors/3-safari.png
Normal file
After Width: | Height: | Size: 4.3 KiB |
BIN
docs/img/sponsors/3-shippo.png
Normal file
After Width: | Height: | Size: 7.2 KiB |
BIN
docs/img/sponsors/3-teonite.png
Normal file
After Width: | Height: | Size: 7.7 KiB |
BIN
docs/img/sponsors/3-thermondo-gmbh.png
Normal file
After Width: | Height: | Size: 20 KiB |
BIN
docs/img/sponsors/3-tivix.png
Normal file
After Width: | Height: | Size: 3.5 KiB |
BIN
docs/img/sponsors/3-trackmaven.png
Normal file
After Width: | Height: | Size: 5.2 KiB |
BIN
docs/img/sponsors/3-transcode.png
Normal file
After Width: | Height: | Size: 8.4 KiB |
BIN
docs/img/sponsors/3-triggered_messaging.png
Normal file
After Width: | Height: | Size: 10 KiB |
BIN
docs/img/sponsors/3-vzzual.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
docs/img/sponsors/3-wildfish.png
Normal file
After Width: | Height: | Size: 4.0 KiB |
|
@ -50,7 +50,7 @@ Some reasons you might want to use REST framework:
|
|||
REST framework requires the following:
|
||||
|
||||
* Python (2.6.5+, 2.7, 3.2, 3.3)
|
||||
* Django (1.3, 1.4, 1.5, 1.6)
|
||||
* Django (1.4.2+, 1.5, 1.6, 1.7)
|
||||
|
||||
The following packages are optional:
|
||||
|
||||
|
@ -201,24 +201,15 @@ General guides to using REST framework.
|
|||
* [2.0 Announcement][rest-framework-2-announcement]
|
||||
* [2.2 Announcement][2.2-announcement]
|
||||
* [2.3 Announcement][2.3-announcement]
|
||||
* [Kickstarter Announcement][kickstarter-announcement]
|
||||
* [Release Notes][release-notes]
|
||||
* [Credits][credits]
|
||||
|
||||
## Development
|
||||
|
||||
If you want to work on REST framework itself, clone the repository, then...
|
||||
|
||||
Build the docs:
|
||||
|
||||
./mkdocs.py
|
||||
|
||||
Run the tests:
|
||||
|
||||
./rest_framework/runtests/runtests.py
|
||||
|
||||
To run the tests against all supported configurations, first install [the tox testing tool][tox] globally, using `pip install tox`, then simply run `tox`:
|
||||
|
||||
tox
|
||||
See the [Contribution guidelines][contributing] for information on how to clone
|
||||
the repository, run the test suite and contribute changes back to REST
|
||||
Framework.
|
||||
|
||||
## Support
|
||||
|
||||
|
@ -325,6 +316,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md
|
||||
[2.2-announcement]: topics/2.2-announcement.md
|
||||
[2.3-announcement]: topics/2.3-announcement.md
|
||||
[kickstarter-announcement]: topics/kickstarter-announcement.md
|
||||
[release-notes]: topics/release-notes.md
|
||||
[credits]: topics/credits.md
|
||||
|
||||
|
|
|
@ -33,6 +33,21 @@
|
|||
})();
|
||||
|
||||
</script>
|
||||
<style>
|
||||
span.fusion-wrap a {
|
||||
display: block;
|
||||
margin-top: 10px;
|
||||
color: black;
|
||||
}
|
||||
|
||||
a.fusion-poweredby {
|
||||
display: block;
|
||||
margin-top: 10px;
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
div.promo {display: none;}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body onload="prettyPrint()" class="{{ page_id }}-page">
|
||||
|
||||
|
@ -106,6 +121,7 @@
|
|||
<li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li>
|
||||
<li><a href="{{ base_url }}/topics/2.2-announcement{{ suffix }}">2.2 Announcement</a></li>
|
||||
<li><a href="{{ base_url }}/topics/2.3-announcement{{ suffix }}">2.3 Announcement</a></li>
|
||||
<li><a href="{{ base_url }}/topics/kickstarter-announcement{{ suffix }}">Kickstarter Announcement</a></li>
|
||||
<li><a href="{{ base_url }}/topics/release-notes{{ suffix }}">Release Notes</a></li>
|
||||
<li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li>
|
||||
</ul>
|
||||
|
@ -169,11 +185,9 @@
|
|||
<div id="table-of-contents">
|
||||
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
||||
{{ toc }}
|
||||
<div>
|
||||
|
||||
{{ ad_block }}
|
||||
|
||||
</div>
|
||||
<div class="promo">
|
||||
{{ ad_block }}
|
||||
</div>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
|
@ -199,6 +213,7 @@
|
|||
<script src="{{ base_url }}/js/jquery-1.8.1-min.js"></script>
|
||||
<script src="{{ base_url }}/js/prettify-1.0.js"></script>
|
||||
<script src="{{ base_url }}/js/bootstrap-2.1.1-min.js"></script>
|
||||
|
||||
<script>
|
||||
//$('.side-nav').scrollspy()
|
||||
var shiftWindow = function() { scrollBy(0, -50) };
|
||||
|
|
158
docs/topics/2.4-accouncement.md
Normal file
|
@ -0,0 +1,158 @@
|
|||
# REST framework 2.4 announcement
|
||||
|
||||
The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series.
|
||||
|
||||
## Version requirements
|
||||
|
||||
Support for Django 1.3 has been dropped.
|
||||
The lowest supported version of Django is now 1.4.2.
|
||||
|
||||
The current plan is for REST framework to remain in lockstep with [Django's long-term support policy][lts-releases].
|
||||
|
||||
## Django 1.7 support
|
||||
|
||||
The optional authtoken application now includes support for *both* Django 1.7 schema migrations, *and* for old-style `south` migrations.
|
||||
|
||||
**If you are using authtoken, and you want to continue using `south`, you must upgrade your `south` package to version 1.0.**
|
||||
|
||||
## Updated test runner
|
||||
|
||||
We now have a new test runner for developing against the project,, that uses the excellent [py.test](http://pytest.org) library.
|
||||
|
||||
To use it make sure you have first installed the test requirements.
|
||||
|
||||
pip install -r requirements-test.txt
|
||||
|
||||
Then run the `runtests.py` script.
|
||||
|
||||
./runtests.py
|
||||
|
||||
The new test runner also includes [flake8](https://flake8.readthedocs.org) code linting, which should help keep our coding style consistent.
|
||||
|
||||
#### Test runner flags
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
./runtests -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
./runtests --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
./runtests --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
./runtests --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
./runtests MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
./runtests 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.
|
||||
|
||||
## Improved viewset routing
|
||||
|
||||
The `@action` and `@link` decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs.
|
||||
|
||||
The `@action` and `@link` decorators have now been moved to pending deprecation, and the `@list_route` and `@detail_route` decroators have been introduced.
|
||||
|
||||
Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a `pk` argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
A viewset that provides the standard actions
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
|
||||
@detail_route(methods=['post'])
|
||||
def set_password(self, request, pk=None):
|
||||
user = self.get_object()
|
||||
serializer = PasswordSerializer(data=request.DATA)
|
||||
if serializer.is_valid():
|
||||
user.set_password(serializer.data['password'])
|
||||
user.save()
|
||||
return Response({'status': 'password set'})
|
||||
else:
|
||||
return Response(serializer.errors,
|
||||
status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@list_route()
|
||||
def recent_users(self, request):
|
||||
recent_users = User.objects.all().order('-last_login')
|
||||
page = self.paginate_queryset(recent_users)
|
||||
serializer = self.get_pagination_serializer(page)
|
||||
return Response(serializer.data)
|
||||
|
||||
For more details, see the [viewsets documentation](../api-guide/viewsets.md).
|
||||
|
||||
## Throttle behavior
|
||||
|
||||
There's one bugfix in 2.4 that's worth calling out, as it will *invalidate existing throttle caches* when you upgrade.
|
||||
|
||||
We've now fixed a typo on the `cache_format` attribute. Previously this was named `"throtte_%(scope)s_%(ident)s"`, it is now `"throttle_%(scope)s_%(ident)s"`.
|
||||
|
||||
If you're concerned about the invalidation you have two options.
|
||||
|
||||
* Manually pre-populate your cache with the fixed version.
|
||||
* Set the `cache_format` attribute on your throttle class in order to retain the previous incorrect spelling.
|
||||
|
||||
## Other features
|
||||
|
||||
There are also a number of other features and bugfixes as [listed in the release notes][2-4-release-notes]. In particular these include:
|
||||
|
||||
[Customizable view name and description functions][view-name-and-description-settings] for use with the browsable API, by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings.
|
||||
|
||||
Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting.
|
||||
|
||||
## Deprecations
|
||||
|
||||
All API changes in 2.3 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
|
||||
|
||||
All API changes in 2.3 that previously raised `DeprecationWarning` have now been removed entirely.
|
||||
|
||||
Furter details on these deprecations is available in the [2.3 announcement][2-3-announcement].
|
||||
|
||||
## Labels and milestones
|
||||
|
||||
Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process.
|
||||
|
||||
The [labels that we use in GitHub][github-labels] have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state.
|
||||
|
||||
We've also [started using milestones][github-milestones] in order to track tickets against particular releases.
|
||||
|
||||
---
|
||||
|
||||
![Labels and milestones](../img/labels-and-milestones.png)
|
||||
|
||||
**Above**: *Overview of our current use of labels and milestones in GitHub.*
|
||||
|
||||
---
|
||||
|
||||
We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant.
|
||||
|
||||
## Next steps
|
||||
|
||||
The next planned release will be 3.0, featuring an improved and simplified serializer implementation.
|
||||
|
||||
Once again, many thanks to all the generous [backers and sponsors][kickstarter-sponsors] who've helped make this possible!
|
||||
|
||||
[lts-releases]: https://docs.djangoproject.com/en/dev/internals/release-process/#long-term-support-lts-releases
|
||||
[2-4-release-notes]: ./topics/release-notes/#240
|
||||
[view-name-and-description-settings]: ../api-guide/settings/#view-names-and-descriptions
|
||||
[client-ip-identification]: ../api-guide/throttling/#how-clients-are-identified
|
||||
[2-3-announcement]: ./topics/2.3-announcement
|
||||
[github-labels]: https://github.com/tomchristie/django-rest-framework/issues
|
||||
[github-milestones]: https://github.com/tomchristie/django-rest-framework/milestones
|
||||
[kickstarter-sponsors]: ./topics/kickstarter-announcement/#sponsors
|
|
@ -69,6 +69,7 @@ For more specific CSS tweaks than simply overriding the default bootstrap theme
|
|||
|
||||
All of the blocks available in the browsable API base template that can be used in your `api.html`.
|
||||
|
||||
* `body` - The entire html `<body>`.
|
||||
* `bodyclass` - Class attribute for the `<body>` tag, empty by default.
|
||||
* `bootstrap_theme` - CSS for the Bootstrap theme.
|
||||
* `bootstrap_navbar_variant` - CSS class for the navbar.
|
||||
|
@ -167,10 +168,10 @@ You can now add the `autocomplete_light.ChoiceWidget` widget to the serializer f
|
|||
[bootstrap]: http://getbootstrap.com
|
||||
[cerulean]: ../img/cerulean.png
|
||||
[slate]: ../img/slate.png
|
||||
[bcustomize]: http://twitter.github.com/bootstrap/customize.html#variables
|
||||
[bcustomize]: http://getbootstrap.com/2.3.2/customize.html
|
||||
[bswatch]: http://bootswatch.com/
|
||||
[bcomponents]: http://twitter.github.com/bootstrap/components.html
|
||||
[bcomponentsnav]: http://twitter.github.com/bootstrap/components.html#navbar
|
||||
[bcomponents]: http://getbootstrap.com/2.3.2/components.html
|
||||
[bcomponentsnav]: http://getbootstrap.com/2.3.2/components.html#navbar
|
||||
[autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
|
||||
[django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
|
||||
[django-autocomplete-light-install]: http://django-autocomplete-light.readthedocs.org/en/latest/#install
|
||||
|
|
|
@ -62,10 +62,44 @@ To run the tests, clone the repository, and then:
|
|||
virtualenv env
|
||||
source env/bin/activate
|
||||
pip install -r requirements.txt
|
||||
pip install -r optionals.txt
|
||||
pip install -r requirements-test.txt
|
||||
|
||||
# Run the tests
|
||||
rest_framework/runtests/runtests.py
|
||||
./runtests.py
|
||||
|
||||
### Test options
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
./runtests -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
./runtests --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
./runtests --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
./runtests --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
./runtests MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
./runtests test_this_method
|
||||
|
||||
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
|
||||
|
||||
### Running against multiple environments
|
||||
|
||||
You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
|
||||
|
||||
|
|
|
@ -95,7 +95,7 @@ You can modify the response behavior to `OPTIONS` requests by overriding the `me
|
|||
|
||||
To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.
|
||||
|
||||
In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the *media types* that are used. The available actions take may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.
|
||||
In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the *media types* that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.
|
||||
|
||||
To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.
|
||||
|
||||
|
|
164
docs/topics/kickstarter-announcement.md
Normal file
|
@ -0,0 +1,164 @@
|
|||
# Kickstarting Django REST framework 3
|
||||
|
||||
---
|
||||
|
||||
<iframe width="480" height="360" src="https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3/widget/video.html" frameborder="0" scrolling="no"> </iframe>
|
||||
|
||||
---
|
||||
|
||||
In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.
|
||||
|
||||
## Project details
|
||||
|
||||
This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:
|
||||
|
||||
* Faster, simpler and easier-to-use serializers.
|
||||
* An alternative admin-style interface for the browsable API.
|
||||
* Search and filtering controls made accessible in the browsable API.
|
||||
* Alternative API pagination styles.
|
||||
* Documentation around API versioning.
|
||||
* Triage of outstanding tickets.
|
||||
* Improving the ongoing quality and maintainability of the project.
|
||||
|
||||
Full details are available now on the [project page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3).
|
||||
|
||||
If you're interested in helping make sustainable open source development a reality please [visit the Kickstarter page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) and consider funding the project.
|
||||
|
||||
I can't wait to see where this takes us!
|
||||
|
||||
Many thanks to everyone for your support so far,
|
||||
|
||||
Tom Christie :)
|
||||
|
||||
---
|
||||
|
||||
## Sponsors
|
||||
|
||||
We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.
|
||||
|
||||
---
|
||||
|
||||
### Platinum sponsors
|
||||
|
||||
Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.
|
||||
|
||||
<ul class="sponsor diamond">
|
||||
<li><a href="https://www.eventbrite.com/" rel="nofollow" style="background-image:url(../img/sponsors/0-eventbrite.png);">Eventbrite</a></li>
|
||||
</ul>
|
||||
|
||||
<ul class="sponsor platinum">
|
||||
<li><a href="https://www.divio.ch/" rel="nofollow" style="background-image:url(../img/sponsors/1-divio.png);">Divio</a></li>
|
||||
<li><a href="http://company.onlulu.com/en/" rel="nofollow" style="background-image:url(../img/sponsors/1-lulu.png);">Lulu</a></li>
|
||||
<li><a href="https://p.ota.to/" rel="nofollow" style="background-image:url(../img/sponsors/1-potato.png);">Potato</a></li>
|
||||
<li><a href="http://www.wiredrive.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-wiredrive.png);">Wiredrive</a></li>
|
||||
<li><a href="http://www.cyaninc.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-cyan.png);">Cyan</a></li>
|
||||
<li><a href="https://www.runscope.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-runscope.png);">Runscope</a></li>
|
||||
<li><a href="http://simpleenergy.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-simple-energy.png);">Simple Energy</a></li>
|
||||
<li><a href="http://vokalinteractive.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-vokal_interactive.png);">VOKAL Interactive</a></li>
|
||||
<li><a href="http://www.purplebit.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-purplebit.png);">Purple Bit</a></li>
|
||||
<li><a href="http://www.kuwaitnet.net/" rel="nofollow" style="background-image:url(../img/sponsors/1-kuwaitnet.png);">KuwaitNET</a></li>
|
||||
</ul>
|
||||
|
||||
<div style="clear: both"></div>
|
||||
|
||||
---
|
||||
|
||||
### Gold sponsors
|
||||
|
||||
Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.
|
||||
|
||||
<ul class="sponsor gold">
|
||||
<li><a href="https://laterpay.net/" rel="nofollow" style="background-image:url(../img/sponsors/2-laterpay.png);">LaterPay</a></li>
|
||||
<li><a href="https://www.schubergphilis.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-schuberg_philis.png);">Schuberg Philis</a></li>
|
||||
<li><a href="http://prorenata.se/" rel="nofollow" style="background-image:url(../img/sponsors/2-prorenata.png);">ProReNata AB</a></li>
|
||||
<li><a href="https://www.sgawebsites.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-sga.png);">SGA Websites</a></li>
|
||||
<li><a href="http://www.sirono.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-sirono.png);">Sirono</a></li>
|
||||
<li><a href="http://www.vinta.com.br/" rel="nofollow" style="background-image:url(../img/sponsors/2-vinta.png);">Vinta Software Studio</a></li>
|
||||
<li><a href="http://www.rapasso.nl/index.php/en" rel="nofollow" style="background-image:url(../img/sponsors/2-rapasso.png);">Rapasso</a></li>
|
||||
<li><a href="https://mirusresearch.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-mirus_research.png);">Mirus Research</a></li>
|
||||
<li><a href="http://hipolabs.com" rel="nofollow" style="background-image:url(../img/sponsors/2-hipo.png);">Hipo</a></li>
|
||||
<li><a href="http://www.byte.nl" rel="nofollow" style="background-image:url(../img/sponsors/2-byte.png);">Byte</a></li>
|
||||
<li><a href="http://lightningkite.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-lightning_kite.png);">Lightning Kite</a></li>
|
||||
<li><a href="https://opbeat.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-opbeat.png);">Opbeat</a></li>
|
||||
<li><a href="https://koordinates.com" rel="nofollow" style="background-image:url(../img/sponsors/2-koordinates.png);">Koordinates</a></li>
|
||||
<li><a href="http://pulsecode.ca" rel="nofollow" style="background-image:url(../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li>
|
||||
<li><a href="http://singinghorsestudio.com" rel="nofollow" style="background-image:url(../img/sponsors/2-singing-horse.png);">Singing Horse Studio. Ltd.</a></li>
|
||||
<li><a href="https://www.heroku.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-heroku.png);">Heroku</a></li>
|
||||
<li><a href="https://www.galileo-press.de/" rel="nofollow" style="background-image:url(../img/sponsors/2-galileo_press.png);">Galileo Press</a></li>
|
||||
<li><a href="http://www.securitycompass.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-security_compass.png);">Security Compass</a></li>
|
||||
<li><a href="https://www.djangoproject.com/foundation/" rel="nofollow" style="background-image:url(../img/sponsors/2-django.png);">Django Software Foundation</a></li>
|
||||
<li><a href="http://www.hipflaskapp.com" rel="nofollow" style="background-image:url(../img/sponsors/2-hipflask.png);">Hipflask</a></li>
|
||||
<li><a href="http://www.crate.io/" rel="nofollow" style="background-image:url(../img/sponsors/2-crate.png);">Crate</a></li>
|
||||
<li><a href="http://crypticocorp.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-cryptico.png);">Cryptico Corp</a></li>
|
||||
<li><a href="http://www.nexthub.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-nexthub.png);">NextHub</a></li>
|
||||
<li><a href="https://www.compile.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-compile.png);">Compile</a></li>
|
||||
<li><a href="http://envisionlinux.org/blog" rel="nofollow">Envision Linux</a></li>
|
||||
</ul>
|
||||
|
||||
<div style="clear: both; padding-bottom: 40px;"></div>
|
||||
|
||||
**Individual backers**: Simon Haugk.
|
||||
|
||||
---
|
||||
|
||||
### Silver sponsors
|
||||
|
||||
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have choosen to privately support the project at this level.
|
||||
|
||||
<ul class="sponsor silver">
|
||||
<li><a href="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
|
||||
<li><a href="http://wildfish.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-wildfish.png);">Wildfish</a></li>
|
||||
<li><a href="http://www.thermondo.de/" rel="nofollow" style="background-image:url(../img/sponsors/3-thermondo-gmbh.png);">Thermondo GmbH</a></li>
|
||||
<li><a href="http://providenz.fr/" rel="nofollow" style="background-image:url(../img/sponsors/3-providenz.png);">Providenz</a></li>
|
||||
<li><a href="https://www.alwaysdata.com" rel="nofollow" style="background-image:url(../img/sponsors/3-alwaysdata.png);">alwaysdata.com</a></li>
|
||||
<li><a href="http://www.triggeredmessaging.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-triggered_messaging.png);">Triggered Messaging</a></li>
|
||||
<li><a href="https://www.ipushpull.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-ipushpull.png);">PushPull Technology Ltd</a></li>
|
||||
<li><a href="http://www.transcode.de/" rel="nofollow" style="background-image:url(../img/sponsors/3-transcode.png);">Transcode</a></li>
|
||||
<li><a href="https://garfo.io/" rel="nofollow" style="background-image:url(../img/sponsors/3-garfo.png);">Garfo</a></li>
|
||||
<li><a href="https://goshippo.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-shippo.png);">Shippo</a></li>
|
||||
<li><a href="http://www.gizmag.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-gizmag.png);">Gizmag</a></li>
|
||||
<li><a href="http://www.tivix.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-tivix.png);">Tivix</a></li>
|
||||
<li><a href="http://www.safaribooksonline.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-safari.png);">Safari</a></li>
|
||||
<li><a href="http://brightloop.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-brightloop.png);">Bright Loop</a></li>
|
||||
<li><a href="http://www.aba-systems.com.au/" rel="nofollow" style="background-image:url(../img/sponsors/3-aba.png);">ABA Systems</a></li>
|
||||
<li><a href="http://beefarm.ru/" rel="nofollow" style="background-image:url(../img/sponsors/3-beefarm.png);">beefarm.ru</a></li>
|
||||
<li><a href="http://www.vzzual.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-vzzual.png);">Vzzual.com</a></li>
|
||||
<li><a href="http://infinite-code.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-infinite_code.png);">Infinite Code</a></li>
|
||||
<li><a href="http://crosswordtracker.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-crosswordtracker.png);">Crossword Tracker</a></li>
|
||||
<li><a href="https://www.pkgfarm.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-pkgfarm.png);">PkgFarm</a></li>
|
||||
<li><a href="http://life.tl/" rel="nofollow" style="background-image:url(../img/sponsors/3-life_the_game.png);">Life. The Game.</a></li>
|
||||
<li><a href="http://blimp.io/" rel="nofollow" style="background-image:url(../img/sponsors/3-blimp.png);">Blimp</a></li>
|
||||
<li><a href="http://pathwright.com" rel="nofollow" style="background-image:url(../img/sponsors/3-pathwright.png);">Pathwright</a></li>
|
||||
<li><a href="http://fluxility.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-fluxility.png);">Fluxility</a></li>
|
||||
<li><a href="http://teonite.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-teonite.png);">Teonite</a></li>
|
||||
<li><a href="http://trackmaven.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-trackmaven.png);">TrackMaven</a></li>
|
||||
<li><a href="http://www.phurba.net/" rel="nofollow" style="background-image:url(../img/sponsors/3-phurba.png);">Phurba</a></li>
|
||||
<li><a href="http://www.nephila.co.uk/" rel="nofollow" style="background-image:url(../img/sponsors/3-nephila.png);">Nephila</a></li>
|
||||
<li><a href="http://www.aditium.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-aditium.png);">Aditium</a></li>
|
||||
<li><a href="http://www.eyesopen.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-openeye.png);">OpenEye Scientific Software</a></li>
|
||||
<li><a href="https://holvi.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-holvi.png);">Holvi</a></li>
|
||||
<li><a href="http://cantemo.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-cantemo.gif);">Cantemo</a></li>
|
||||
<li><a href="https://www.makespace.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-makespace.png);">MakeSpace</a></li>
|
||||
<li><a href="https://www.ax-semantics.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-ax_semantics.png);">AX Semantics</a></li>
|
||||
<li><a href="http://istrategylabs.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-isl.png);">ISL</a></li>
|
||||
</ul>
|
||||
|
||||
<div style="clear: both; padding-bottom: 40px;"></div>
|
||||
|
||||
**Individual backers**: Paul Hallet, <a href="http://www.paulwhippconsulting.com/">Paul Whipp</a>, Dylan Roy, Jannis Leidel, <a href="https://linovia.com/en/">Xavier Ordoquy</a>, <a href="http://spielmannsolutions.com/">Johannes Spielmann</a>, <a href="http://brooklynhacker.com/">Rob Spectre</a>, <a href="http://chrisheisel.com/">Chris Heisel</a>, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.
|
||||
|
||||
---
|
||||
|
||||
### Advocates
|
||||
|
||||
The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!
|
||||
|
||||
**Individual backers**: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, Décébal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkkä, Charalampos Papaloizou, Nikolai Røed Kristiansen, Antoni Aloy López, Celia Oakley, Michał Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.
|
||||
|
||||
**Corporate backers**: Savannah Informatics, Prism Skylabs, Musical Operating Devices.
|
||||
|
||||
---
|
||||
|
||||
### Supporters
|
||||
|
||||
There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!
|
|
@ -38,8 +38,59 @@ You can determine your currently installed version using `pip freeze`:
|
|||
|
||||
---
|
||||
|
||||
## 2.4.x series
|
||||
|
||||
### 2.4.0
|
||||
|
||||
**Django version requirements**: The lowest supported version of Django is now 1.4.2.
|
||||
|
||||
**South version requirements**: This note applies to any users using the optional `authtoken` application, which includes an associated database migration. You must now *either* upgrade your `south` package to version 1.0, *or* instead use the built-in migration support available with Django 1.7.
|
||||
|
||||
* Added compatibility with Django 1.7's database migration support.
|
||||
* New test runner, using `py.test`.
|
||||
* `@detail_route` and `@list_route` decorators replace `@action` and `@link`.
|
||||
* Support customizable view name and description functions, using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings.
|
||||
* Added `NUM_PROXIES` setting for smarter client IP identification.
|
||||
* Added `MAX_PAGINATE_BY` setting and `max_paginate_by` generic view attribute.
|
||||
* Added `cache` attribute to throttles to allow overriding of default cache.
|
||||
* Added `lookup_value_regex` attribute to routers, to allow the URL argument matching to be constrainted by the user.
|
||||
* Added `allow_none` option to `CharField`.
|
||||
* Support Django's standard `status_code` class attribute on responses.
|
||||
* More intuitive behavior on the test client, as `client.logout()` now also removes any credentials that have been set.
|
||||
* Bugfix: `?page_size=0` query parameter now falls back to default page size for view, instead of always turning pagination off.
|
||||
* Bugfix: Always uppercase `X-Http-Method-Override` methods.
|
||||
* Bugfix: Copy `filter_backends` list before returning it, in order to prevent view code from mutating the class attribute itself.
|
||||
* Bugfix: Set the `.action` attribute on viewsets when introspected by `OPTIONS` for testing permissions on the view.
|
||||
* Bugfix: Ensure `ValueError` raised during deserialization results in a error list rather than a single error. This is now consistent with other validation errors.
|
||||
* Bugfix: Fix `cache_format` typo on throttle classes, was `"throtte_%(scope)s_%(ident)s"`. Note that this will invalidate existing throttle caches.
|
||||
|
||||
---
|
||||
|
||||
## 2.3.x series
|
||||
|
||||
### 2.3.14
|
||||
|
||||
**Date**: 12th June 2014
|
||||
|
||||
* **Security fix**: Escape request path when it is include as part of the login and logout links in the browsable API.
|
||||
* `help_text` and `verbose_name` automatically set for related fields on `ModelSerializer`.
|
||||
* Fix nested serializers linked through a backward foreign key relation.
|
||||
* Fix bad links for the `BrowsableAPIRenderer` with `YAMLRenderer`.
|
||||
* Add `UnicodeYAMLRenderer` that extends `YAMLRenderer` with unicode.
|
||||
* Fix `parse_header` argument convertion.
|
||||
* Fix mediatype detection under Python 3.
|
||||
* Web browseable API now offers blank option on dropdown when the field is not required.
|
||||
* `APIException` representation improved for logging purposes.
|
||||
* Allow source="*" within nested serializers.
|
||||
* Better support for custom oauth2 provider backends.
|
||||
* Fix field validation if it's optional and has no value.
|
||||
* Add `SEARCH_PARAM` and `ORDERING_PARAM`.
|
||||
* Fix `APIRequestFactory` to support arguments within the url string for GET.
|
||||
* Allow three transport modes for access tokens when accessing a protected resource.
|
||||
* Fix `QueryDict` encoding on request objects.
|
||||
* Ensure throttle keys do not contain spaces, as those are invalid if using `memcached`.
|
||||
* Support `blank_display_value` on `ChoiceField`.
|
||||
|
||||
### 2.3.13
|
||||
|
||||
**Date**: 6th March 2014
|
||||
|
@ -112,11 +163,11 @@ You can determine your currently installed version using `pip freeze`:
|
|||
* Bugfix: `client.force_authenticate(None)` should also clear session info if it exists.
|
||||
* Bugfix: Client sending empty string instead of file now clears `FileField`.
|
||||
* Bugfix: Empty values on ChoiceFields with `required=False` now consistently return `None`.
|
||||
* Bugfix: Clients setting `page=0` now simply returns the default page size, instead of disabling pagination. [*]
|
||||
* Bugfix: Clients setting `page_size=0` now simply returns the default page size, instead of disabling pagination. [*]
|
||||
|
||||
---
|
||||
|
||||
[*] Note that the change in `page=0` behaviour fixes what is considered to be a bug in how clients can effect the pagination size. However if you were relying on this behavior you will need to add the following mixin to your list views in order to preserve the existing behavior.
|
||||
[*] Note that the change in `page_size=0` behaviour fixes what is considered to be a bug in how clients can effect the pagination size. However if you were relying on this behavior you will need to add the following mixin to your list views in order to preserve the existing behavior.
|
||||
|
||||
class DisablePaginationMixin(object):
|
||||
def get_paginate_by(self, queryset=None):
|
||||
|
|
|
@ -104,7 +104,7 @@ Don't forget to sync the database for the first time.
|
|||
|
||||
## Creating a Serializer class
|
||||
|
||||
The first thing we need to get started on our Web API is provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following.
|
||||
The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following.
|
||||
|
||||
from django.forms import widgets
|
||||
from rest_framework import serializers
|
||||
|
@ -143,7 +143,7 @@ The first thing we need to get started on our Web API is provide a way of serial
|
|||
# Create new instance
|
||||
return Snippet(**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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
|
|
@ -44,11 +44,11 @@ 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
|
||||
python manage.py syncdb
|
||||
|
||||
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.
|
||||
|
||||
python ./manage.py createsuperuser
|
||||
python manage.py createsuperuser
|
||||
|
||||
## Adding endpoints for our User models
|
||||
|
||||
|
@ -129,7 +129,7 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai
|
|||
|
||||
If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
|
||||
|
||||
We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file.
|
||||
We can add a login view for use with the browsable API, by editing the URLconf in our project-level `urls.py` file.
|
||||
|
||||
Add the following import at the top of the file:
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ At the moment relationships within our API are represented by using primary keys
|
|||
|
||||
## Creating an endpoint for the root of our API
|
||||
|
||||
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.
|
||||
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
|
||||
|
@ -29,7 +29,7 @@ Unlike all our other API endpoints, we don't want to use JSON, but instead just
|
|||
|
||||
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
|
||||
|
||||
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your snippets.views add:
|
||||
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add:
|
||||
|
||||
from rest_framework import renderers
|
||||
from rest_framework.response import Response
|
||||
|
@ -43,7 +43,7 @@ Instead of using a concrete generic view, we'll use the base class for represent
|
|||
return Response(snippet.highlighted)
|
||||
|
||||
As usual we need to add the new views that we've created in to our URLconf.
|
||||
We'll add a url pattern for our new API root:
|
||||
We'll add a url pattern for our new API root in `snippets/urls.py`:
|
||||
|
||||
url(r'^$', 'api_root'),
|
||||
|
||||
|
@ -73,7 +73,7 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial
|
|||
* Relationships use `HyperlinkedRelatedField`,
|
||||
instead of `PrimaryKeyRelatedField`.
|
||||
|
||||
We can easily re-write our existing serializers to use hyperlinking.
|
||||
We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add:
|
||||
|
||||
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
|
||||
owner = serializers.Field(source='owner.username')
|
||||
|
@ -105,7 +105,7 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p
|
|||
* Our user serializer includes a field that refers to `'snippet-detail'`.
|
||||
* Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`.
|
||||
|
||||
After adding all those names into our URLconf, our final `'urls.py'` file should look something like this:
|
||||
After adding all those names into our URLconf, our final `snippets/urls.py` file should look something like this:
|
||||
|
||||
# API endpoints
|
||||
urlpatterns = format_suffix_patterns(patterns('snippets.views',
|
||||
|
|
|
@ -21,11 +21,11 @@ First of all let's refactor our `UserList` and `UserDetail` views into a single
|
|||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
|
||||
Here we've used `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
|
||||
Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
|
||||
|
||||
Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
|
||||
|
||||
from rest_framework.decorators import link
|
||||
from rest_framework.decorators import detail_route
|
||||
|
||||
class SnippetViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
|
@ -39,7 +39,7 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
|
|||
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
|
||||
IsOwnerOrReadOnly,)
|
||||
|
||||
@link(renderer_classes=[renderers.StaticHTMLRenderer])
|
||||
@detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
|
||||
def highlight(self, request, *args, **kwargs):
|
||||
snippet = self.get_object()
|
||||
return Response(snippet.highlighted)
|
||||
|
@ -49,9 +49,9 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
|
|||
|
||||
This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations.
|
||||
|
||||
Notice that we've also used the `@link` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style.
|
||||
Notice that we've also used the `@detail_route` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style.
|
||||
|
||||
Custom actions which use the `@link` decorator will respond to `GET` requests. We could have instead used the `@action` decorator if we wanted an action that responded to `POST` requests.
|
||||
Custom actions which use the `@detail_route` decorator will respond to `GET` requests. We can use the `methods` argument if we wanted an action that responded to `POST` requests.
|
||||
|
||||
## Binding ViewSets to URLs explicitly
|
||||
|
||||
|
@ -85,7 +85,7 @@ In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views
|
|||
|
||||
Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view.
|
||||
|
||||
Now that we've bound our resources into concrete views, that we can register the views with the URL conf as usual.
|
||||
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
|
||||
|
||||
urlpatterns = format_suffix_patterns(patterns('snippets.views',
|
||||
url(r'^$', 'api_root'),
|
||||
|
@ -138,7 +138,7 @@ You can review the final [tutorial code][repo] on GitHub, or try out a live exam
|
|||
|
||||
## Onwards and upwards
|
||||
|
||||
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
|
||||
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:
|
||||
|
||||
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
|
||||
* Join the [REST framework discussion group][group], and help build the community.
|
||||
|
|