diff options
| author | Tom Christie | 2013-06-05 13:33:19 +0100 |
|---|---|---|
| committer | Tom Christie | 2013-06-05 13:33:19 +0100 |
| commit | de00ec95c3007dd90b5b01f7486b430699ea63c1 (patch) | |
| tree | d2ce8037d446fd9133b3d6a77ebcc49350d7ebc3 /docs | |
| parent | 9428d6ddb5ebc2d5d9c8557a52be09f0def69cca (diff) | |
| parent | 2ca243a1144bb2a5461767a21ed14dec1d2b8dc2 (diff) | |
| download | django-rest-framework-de00ec95c3007dd90b5b01f7486b430699ea63c1.tar.bz2 | |
Merge master
Diffstat (limited to 'docs')
34 files changed, 605 insertions, 214 deletions
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index c2f73901..09491f02 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -86,7 +86,7 @@ Note that when a request may successfully authenticate, but still be denied perm Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level. -If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`. +If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`. # this can go in either server config, virtual host, directory or .htaccess WSGIPassAuthorization On @@ -216,9 +216,9 @@ If you're using an AJAX style API with SessionAuthentication, you'll need to mak ## OAuthAuthentication -This authentication uses [OAuth 1.0a][oauth-1.0a] authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests. +This authentication uses [OAuth 1.0a][oauth-1.0a] authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests. -This authentication class depends on the optional `django-oauth-plus` and `oauth2` packages. In order to make it work you must install these packages and add `oauth_provider` to your `INSTALLED_APPS`: +This authentication class depends on the optional `django-oauth-plus` and `oauth2` packages. In order to make it work you must install these packages and add `oauth_provider` to your `INSTALLED_APPS`: INSTALLED_APPS = ( ... @@ -231,7 +231,7 @@ Don't forget to run `syncdb` once you've added the package. #### Getting started with django-oauth-plus -The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens. +The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens. The `django-oauth-plus` package provides simple foundation for classic 'three-legged' oauth flow. Please refer to [the documentation][django-oauth-plus] for more details. @@ -239,7 +239,7 @@ The `django-oauth-plus` package provides simple foundation for classic 'three-le This authentication uses [OAuth 2.0][rfc6749] authentication scheme. OAuth2 is more simple to work with than OAuth1, and provides much better security than simple token authentication. It is an unauthenticated scheme, and requires you to use an HTTPS connection. -This authentication class depends on the optional [django-oauth2-provider][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS`: +This authentication class depends on the optional [django-oauth2-provider][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS`: INSTALLED_APPS = ( ... @@ -266,9 +266,9 @@ Finally, sync your database. #### Getting started with django-oauth2-provider -The `OAuth2Authentication` class only provides token verification for requests. It doesn't provide authorization flow for your clients. +The `OAuth2Authentication` class only provides token verification for requests. It doesn't provide authorization flow for your clients. -The OAuth 2 authorization flow is taken care by the [django-oauth2-provider][django-oauth2-provider] dependency. A walkthrough is given here, but for more details you should refer to [the documentation][django-oauth2-provider-docs]. +The OAuth 2 authorization flow is taken care by the [django-oauth2-provider][django-oauth2-provider] dependency. A walkthrough is given here, but for more details you should refer to [the documentation][django-oauth2-provider-docs]. To get started: @@ -276,7 +276,7 @@ To get started: You can create a client, either through the shell, or by using the Django admin. -Go to the admin panel and create a new `Provider.Client` entry. It will create the `client_id` and `client_secret` properties for you. +Go to the admin panel and create a new `Provider.Client` entry. It will create the `client_id` and `client_secret` properties for you. ##### 2. Request an access token @@ -333,7 +333,7 @@ The following example will authenticate any incoming request as the user given b try: user = User.objects.get(username=username) except User.DoesNotExist: - raise authenticate.AuthenticationFailed('No such user') + raise exceptions.AuthenticationFailed('No such user') return (user, None) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index e117c370..94fff7e2 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -16,7 +16,7 @@ Serializer fields handle converting between primitive values and internal dataty ## Core arguments -Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: +Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: ### `source` @@ -41,7 +41,9 @@ Defaults to `True`. ### `default` -If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all. +If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all. + +May be set to a function or other callable, in which case the value will be evaluated each time it is used. ### `validators` @@ -56,6 +58,13 @@ A dictionary of error codes to error messages. Used only if rendering the field to HTML. This argument sets the widget that should be used to render the field. +### `label` + +A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. + +### `help_text` + +A text string that may be used as a description of the field in HTML form fields or other descriptive elements. --- @@ -108,11 +117,13 @@ A field that supports both read and write operations. By itself `WritableField` A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. -**Signature:** `ModelField(model_field=<Django ModelField class>)` +The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` + +**Signature:** `ModelField(model_field=<Django ModelField instance>)` ## SerializerMethodField -This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: +This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: from rest_framework import serializers from django.contrib.auth.models import User @@ -151,7 +162,7 @@ or `django.db.models.fields.TextField`. ## URLField -Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. +Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. **Signature:** `CharField(max_length=200, min_length=None)` @@ -197,16 +208,16 @@ If you want to override this behavior, you'll need to declare the `DateTimeField class Meta: model = Comment -Note that by default, datetime representations are deteremined by the renderer in use, although this can be explicitly overridden as detailed below. +Note that by default, datetime representations are determined by the renderer in use, although this can be explicitly overridden as detailed below. In the case of JSON this means the default datetime representation uses the [ECMA 262 date time string specification][ecma262]. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: `2013-01-29T12:34:56.123Z`. **Signature:** `DateTimeField(format=None, input_formats=None)` * `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `datetime` objects should be returned by `to_native`. In this case the datetime encoding will be determined by the renderer. -* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. +* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. -DateTime format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`) +DateTime format strings may either be [python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`) ## DateField @@ -217,9 +228,9 @@ Corresponds to `django.db.models.fields.DateField` **Signature:** `DateField(format=None, input_formats=None)` * `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `date` objects should be returned by `to_native`. In this case the date encoding will be determined by the renderer. -* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. +* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. -Date format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) +Date format strings may either be [python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) ## TimeField @@ -232,9 +243,9 @@ Corresponds to `django.db.models.fields.TimeField` **Signature:** `TimeField(format=None, input_formats=None)` * `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `time` objects should be returned by `to_native`. In this case the time encoding will be determined by the renderer. -* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. +* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. -Time format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) +Time format strings may either be [python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) ## IntegerField @@ -256,7 +267,7 @@ Corresponds to `django.db.models.fields.DecimalField`. ## FileField -A file representation. Performs Django's standard FileField validation. +A file representation. Performs Django's standard FileField validation. Corresponds to `django.forms.fields.FileField`. @@ -285,7 +296,7 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. # Custom fields -If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects. +If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the initial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects. The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation. diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 50bc6f05..05c997a3 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -2,7 +2,7 @@ # Filtering -> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. +> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. > > — [Django documentation][cite] @@ -77,20 +77,61 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/ # Generic Filtering -As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters. +As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters. + +## Setting filter backends + +The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example. + + REST_FRAMEWORK = { + 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',) + } + +You can also set the filter backends on a per-view, or per-viewset basis, +using the `GenericAPIView` class based views. + + class UserListView(generics.ListAPIView): + queryset = User.objects.all() + serializer = UserSerializer + filter_backends = (filters.DjangoFilterBackend,) + +## Filtering and object lookups + +Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. + +For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance: + + http://example.com/api/products/4675/?category=clothing&max_price=10.00 + +## Overriding the initial queryset + +Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this: + + class PurchasedProductsList(generics.ListAPIView): + """ + Return a list of all the products that the authenticated + user has ever purchased, with optional filtering. + """ + model = Product + serializer_class = ProductSerializer + filter_class = ProductFilter + + def get_queryset(self): + user = self.request.user + return user.purchase_set.all() + +--- + +# API Guide ## DjangoFilterBackend +The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter]. + To use REST framework's `DjangoFilterBackend`, first install `django-filter`. pip install django-filter -You must also set the filter backend to `DjangoFilterBackend` in your settings: - - REST_FRAMEWORK = { - 'DEFAULT_FILTER_BACKENDS': ['rest_framework.filters.DjangoFilterBackend'] - } - #### Specifying filter fields @@ -134,33 +175,72 @@ For more details on using filter sets see the [django-filter documentation][djan * By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting. * When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].) * `django-filter` supports filtering across relationships, using Django's double-underscore syntax. +* For Django 1.3 support, make sure to install `django-filter` version 0.5.4, as later versions drop support for 1.3. --- -## Filtering and object lookups +## SearchFilter -Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. +The `SearchFilterBackend` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin]. -For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance: +The `SearchFilterBackend` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`. - http://example.com/api/products/4675/?category=clothing&max_price=10.00 + class UserListView(generics.ListAPIView): + queryset = User.objects.all() + serializer = UserSerializer + filter_backends = (filters.SearchFilter,) + search_fields = ('username', 'email') -## Overriding the initial queryset - -Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this: +This will allow the client to filter the items in the list by making queries such as: + + http://example.com/api/users?search=russell + +You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: + + search_fields = ('username', 'email', 'profile__profession') + +By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. + +The search behavior may be restricted by prepending various characters to the `search_fields`. + +* '^' Starts-with search. +* '=' Exact matches. +* '@' Full-text search. (Currently only supported Django's MySQL backend.) + +For example: + + search_fields = ('=username', '=email') + +For more details, see the [Django documentation][search-django-admin]. + +--- + +## OrderingFilter + +The `OrderingFilter` class supports simple query parameter controlled ordering of results. To specify the result order, set a query parameter named `'ordering'` to the required field name. For example: + + http://example.com/api/users?ordering=username + +The client may also specify reverse orderings by prefixing the field name with '-', like so: + + http://example.com/api/users?ordering=-username + +Multiple orderings may also be specified: + + http://example.com/api/users?ordering=account,username + +If an `ordering` attribute is set on the view, this will be used as the default ordering. + +Typically you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results. + + class UserListView(generics.ListAPIView): + queryset = User.objects.all() + serializer = UserSerializer + filter_backends = (filters.OrderingFilter,) + ordering = ('username',) + +The `ordering` attribute may be either a string or a list/tuple of strings. - class PurchasedProductsList(generics.ListAPIView): - """ - Return a list of all the products that the authenticated - user has ever purchased, with optional filtering. - """ - model = Product - serializer_class = ProductSerializer - filter_class = ProductFilter - - def get_queryset(self): - user = self.request.user - return user.purchase_set.all() --- # Custom generic filtering @@ -169,15 +249,23 @@ You can also provide your own generic filtering backend, or write an installable To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset. -To install the filter backend, set the `'DEFAULT_FILTER_BACKENDS'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class. +As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user. -For example: +## Example - REST_FRAMEWORK = { - 'DEFAULT_FILTER_BACKENDS': ['custom_filters.CustomFilterBackend'] - } +For example, you might need to restrict users to only being able to see objects they created. + + class IsOwnerFilterBackend(filters.BaseFilterBackend): + """ + Filter that only allows users to see their own objects. + """ + def filter_queryset(self, request, queryset, view): + return queryset.filter(owner=request.user) + +We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API. [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters [django-filter]: https://github.com/alex/django-filter [django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html [nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py +[search-django-admin]: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index dae3dea3..529738e3 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -58,11 +58,11 @@ Also note that `format_suffix_patterns` does not support descending into `includ ## Accept headers vs. format suffixes -There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead. +There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead. It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: -“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2] +“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2] The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern. diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index a30bfb21..20b9440b 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -34,7 +34,7 @@ For more complex cases you might also want to override various methods on the vi """ Use smaller pagination for HTML representations. """ - self.request.accepted_renderer.format == 'html': + if self.request.accepted_renderer.format == 'html': return 20 return 100 @@ -71,7 +71,7 @@ The following attributes control the basic view behavior. The following attibutes are used to control pagination when used with list views. * `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`. -* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. +* `paginate_by_param` - The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. * `pagination_serializer_class` - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting. * `page_kwarg` - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to `'page'`. @@ -164,6 +164,52 @@ You won't typically need to override the following methods, although you might n --- +# Mixins + +The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behavior. + +## ListModelMixin + +Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset. + +If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. + +If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. + +## CreateModelMixin + +Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance. + +If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value. + +If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. + +## RetrieveModelMixin + +Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response. + +If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`. + +## UpdateModelMixin + +Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. + +Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests. + +If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response. + +If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response. + +If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. + +## DestroyModelMixin + +Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance. + +If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`. + +--- + # Concrete View Classes The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. @@ -242,59 +288,49 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyMod --- -# Mixins - -The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behavior. - -## ListModelMixin - -Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset. - -If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. - -If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. - -Should be mixed in with [MultipleObjectAPIView]. +# Customizing the generic views -## CreateModelMixin +Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed. -Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance. +## Creating custom mixins -If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value. - -If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. - -Should be mixed in with any [GenericAPIView]. - -## RetrieveModelMixin +For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following: -Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response. - -If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`. - -Should be mixed in with [SingleObjectAPIView]. - -## UpdateModelMixin - -Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. - -Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests. - -If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response. + class MultipleFieldLookupMixin(object): + """ + Apply this mixin to any view or viewset to get multiple field filtering + based on a `lookup_fields` attribute, instead of the default single field filtering. + """ + def get_object(self): + queryset = self.get_queryset() # Get the base queryset + queryset = self.filter_queryset(queryset) # Apply any filter backends + filter = {} + for field in self.lookup_fields: + filter[field] = self.kwargs[field] + return get_object_or_404(queryset, **filter) # Lookup the object -If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response. +You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior. -If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. + class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView): + queryset = User.objects.all() + serializer_class = UserSerializer + lookup_fields = ('account', 'username') -Should be mixed in with [SingleObjectAPIView]. +Using custom mixins is a good option if you have custom behavior that needs to be used -## DestroyModelMixin +## Creating custom base classes -Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance. +If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example: -If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`. + class BaseRetrieveView(MultipleFieldLookupMixin, + generics.RetrieveAPIView): + pass + + class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin, + generics.RetrieveUpdateDestroyAPIView): + pass -Should be mixed in with [SingleObjectAPIView]. +Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project. [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index db0d4b26..2c0a055c 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -2,7 +2,7 @@ # Permissions -> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization. +> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization. > > — [Apple Developer Documentation][cite] @@ -147,7 +147,7 @@ If you need to test if a request is a read operation or a write operation, you s **Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required. -As of version 2.2 this signature has now been replaced with two seperate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed. +As of version 2.2 this signature has now been replaced with two separate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed. For more details see the [2.2 release announcement][2.2-announcement]. diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 756e1562..50c9bc54 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -138,7 +138,7 @@ By default this field is read-write, although you can change this behavior using * `many` - If applied to a to-many relationship, you should set this argument to `True`. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. -* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. +* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. ## SlugRelatedField @@ -196,15 +196,13 @@ Would serialize to a representation like this: 'artist': 'Thom Yorke' 'track_listing': 'http://www.example.com/api/track_list/12/', } - + This field is always read-only. **Arguments**: * `view_name` - The view name that should be used as the target of the relationship. **required**. -* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. -* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`. -* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. +* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. --- @@ -239,7 +237,7 @@ Would serialize to a nested representation like this: 'album_name': 'The Grey Album', 'artist': 'Danger Mouse' 'tracks': [ - {'order': 1, 'title': 'Public Service Annoucement'}, + {'order': 1, 'title': 'Public Service Announcement'}, {'order': 2, 'title': 'What More Can I Say'}, {'order': 3, 'title': 'Encore'}, ... @@ -383,6 +381,15 @@ Note that reverse generic keys, expressed using the `GenericRelation` field, can For more information see [the Django documentation on generic relations][generic-relations]. +## ManyToManyFields with a Through Model + +By default, relational fields that target a ``ManyToManyField`` with a +``through`` model specified are set to read-only. + +If you exlicitly specify a relational field pointing to a +``ManyToManyField`` with a through model, be sure to set ``read_only`` +to ``True``. + ## Advanced Hyperlinked fields If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`. diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index ed733c65..b627c930 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -14,7 +14,7 @@ The set of valid renderers for a view is always defined as a list of classes. W The basic process of content negotiation involves examining the request's `Accept` header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data. -For more information see the documentation on [content negotation][conneg]. +For more information see the documentation on [content negotiation][conneg]. ## Setting the renderers @@ -67,14 +67,46 @@ If your API includes views that can serve both regular webpages and API response ## JSONRenderer -Renders the request data into `JSON`. +Renders the request data into `JSON`, using utf-8 encoding. + +Note that non-ascii characters will be rendered using JSON's `\uXXXX` character escape. For example: + + {"unicode black star": "\u2605"} + +The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. + + { + "unicode black star": "\u2605" + } + +**.media_type**: `application/json` + +**.format**: `'.json'` + +**.charset**: `utf-8` + +## UnicodeJSONRenderer + +Renders the request data into `JSON`, using utf-8 encoding. + +Note that non-ascii characters will not be character escaped. For example: + + {"unicode black star": "★"} The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. + { + "unicode black star": "★" + } + +Both the `JSONRenderer` and `UnicodeJSONRenderer` styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. + **.media_type**: `application/json` **.format**: `'.json'` +**.charset**: `utf-8` + ## JSONPRenderer Renders the request data into `JSONP`. The `JSONP` media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a `JSON` response in a javascript callback. @@ -87,6 +119,8 @@ The javascript callback function must be set by the client including a `callback **.format**: `'.jsonp'` +**.charset**: `utf-8` + ## YAMLRenderer Renders the request data into `YAML`. @@ -97,6 +131,8 @@ Requires the `pyyaml` package to be installed. **.format**: `'.yaml'` +**.charset**: `utf-8` + ## XMLRenderer Renders REST framework's default style of `XML` response content. @@ -109,6 +145,8 @@ If you are considering using `XML` for your API, you may want to consider implem **.format**: `'.xml'` +**.charset**: `utf-8` + ## TemplateHTMLRenderer Renders data to HTML, using Django's standard template rendering. @@ -143,6 +181,8 @@ If you're building websites that use `TemplateHTMLRenderer` along with other ren **.format**: `'.html'` +**.charset**: `utf-8` + See also: `StaticHTMLRenderer` ## StaticHTMLRenderer @@ -163,6 +203,8 @@ You can use `TemplateHTMLRenderer` either to return regular HTML pages using RES **.format**: `'.html'` +**.charset**: `utf-8` + See also: `TemplateHTMLRenderer` ## BrowsableAPIRenderer @@ -173,12 +215,16 @@ Renders data into HTML for the Browsable API. This renderer will determine whic **.format**: `'.api'` +**.charset**: `utf-8` + --- # Custom renderers To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method. +The method should return a bytestring, which wil be used as the body of the HTTP response. + The arguments passed to the `.render()` method are: ### `data` @@ -187,13 +233,13 @@ The request data, as set by the `Response()` instantiation. ### `media_type=None` -Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. +Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`. ### `renderer_context=None` -Optional. If provided, this is a dictionary of contextual information provided by the view. +Optional. If provided, this is a dictionary of contextual information provided by the view. By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`. @@ -205,14 +251,36 @@ The following is an example plaintext renderer that will return a response with from rest_framework import renderers - class PlainText(renderers.BaseRenderer): + class PlainTextRenderer(renderers.BaseRenderer): media_type = 'text/plain' format = 'txt' def render(self, data, media_type=None, renderer_context=None): - if isinstance(data, basestring): - return data - return smart_unicode(data) + return data.encode(self.charset) + +## Setting the character set + +By default renderer classes are assumed to be using the `UTF-8` encoding. To use a different encoding, set the `charset` attribute on the renderer. + + class PlainTextRenderer(renderers.BaseRenderer): + media_type = 'text/plain' + format = 'txt' + charset = 'iso-8859-1' + + def render(self, data, media_type=None, renderer_context=None): + return data.encode(self.charset) + +Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding. + +If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string. + + class JPEGRenderer(renderers.BaseRenderer): + media_type = 'image/jpeg' + format = 'jpg' + charset = None + + def render(self, data, media_type=None, renderer_context=None): + return data --- @@ -252,6 +320,15 @@ For example: data = serializer.data return Response(data) +## Underspecifying the media type + +In some cases you might want a renderer to serve a range of media types. +In this case you can underspecify the media types it should respond to, by using a `media_type` value such as `image/*`, or `*/*`. + +If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the `content_type` attribute. For example: + + return Response(data, content_type='image/png') + ## Designing your media types For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll need to consider the design and usage of your media types in more detail. @@ -274,6 +351,8 @@ Exceptions raised and handled by an HTML renderer will attempt to render using o Templates will render with a `RequestContext` which includes the `status_code` and `details` keys. +**Note**: If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text. + --- # Third party packages @@ -291,6 +370,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers +[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt [cors]: http://www.w3.org/TR/cors/ [cors-docs]: ../topics/ajax-csrf-cors.md [HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index 794f9377..374276dc 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -2,7 +2,7 @@ # Responses -> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. +> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. > > — [Django documentation][cite] @@ -20,7 +20,7 @@ Unless you want to heavily customize REST framework for some reason, you should ## Response() -**Signature:** `Response(data, status=None, template_name=None, headers=None)` +**Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)` Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any python primatives. @@ -34,6 +34,7 @@ Arguments: * `status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes]. * `template_name`: A template name to use if `HTMLRenderer` is selected. * `headers`: A dictionary of HTTP headers to use in the response. +* `content_type`: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly. --- diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 6588d7e5..f16fa946 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -2,7 +2,7 @@ # Routers -> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. +> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. > > — [Ruby on Rails Documentation][cite] @@ -66,6 +66,13 @@ This router includes routes for the standard set of `list`, `create`, `retrieve` <tr><td>POST</td><td>@action decorated method</td></tr> </table> +By default the URLs created by `SimpleRouter` are appending with a trailing slash. +This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example: + + router = SimpleRouter(trailing_slash=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. + ## 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. @@ -83,15 +90,19 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d <tr><td>POST</td><td>@action decorated method</td></tr> </table> +As with `SimpleRouter` the trailing slashs on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router. + + router = DefaultRouter(trailing_slash=False) + # Custom Routers -Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specfic requirements about how the your URLs for your API are strutured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. +Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are strutured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. ## Example -The following example will only route to the `list` and `retrieve` actions, and unlike the routers included by REST framework, it does not use the trailing slash convention. +The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention. class ReadOnlyRouter(SimpleRouter): """ diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index f24fca0f..44ee7e39 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -3,7 +3,7 @@ # Serializers > Expanding the usefulness of the serializers is something that we would -like to address. However, it's not a trivial problem, and it +like to address. However, it's not a trivial problem, and it will take some serious design work. > > — Russell Keith-Magee, [Django users group][cite] @@ -104,11 +104,11 @@ When deserializing a list of items, errors will be returned as a list of diction #### Field-level validation -You can specify custom field-level validation by adding `.validate_<fieldname>` methods to your `Serializer` subclass. These are analagous to `.clean_<fieldname>` methods on Django forms, but accept slightly different arguments. +You can specify custom field-level validation by adding `.validate_<fieldname>` methods to your `Serializer` subclass. These are analogous to `.clean_<fieldname>` methods on Django forms, but accept slightly different arguments. They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided). -Your `validate_<fieldname>` methods should either just return the `attrs` dictionary or raise a `ValidationError`. For example: +Your `validate_<fieldname>` methods should either just return the `attrs` dictionary or raise a `ValidationError`. For example: from rest_framework import serializers @@ -127,7 +127,7 @@ Your `validate_<fieldname>` methods should either just return the `attrs` dictio #### Object-level validation -To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example: +To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example: from rest_framework import serializers @@ -285,7 +285,7 @@ To map the incoming data items to their corresponding object instances, the `.ge There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs. -You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example: +You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example: serializer = AccountSerializer(account, context={'request': request}) serializer.data @@ -333,7 +333,7 @@ The `depth` option should be set to an integer value that indicates the depth of ## Specifying which fields should be read-only -You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so: +You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so: class AccountSerializer(serializers.ModelSerializer): class Meta: @@ -425,7 +425,7 @@ Doing so should be considered advanced usage, and will only be needed if you hav The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes. -For more advanced customization than simply changing the default serializer class you can override various `get_<field_type>_field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`. +For more advanced customization than simply changing the default serializer class you can override various `get_<field_type>_field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`. ### get_pk_field diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index b00ab4c1..8d8c00cf 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -125,7 +125,7 @@ Default: `None` #### PAGINATE_BY_PARAM -The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If set to `None`, clients may not override the default page size. +The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to `None`, clients may not override the default page size. Default: `None` diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index b50c96ae..db2e059c 100644 --- a/docs/api-guide/status-codes.md +++ b/docs/api-guide/status-codes.md @@ -2,7 +2,7 @@ # Status Codes -> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. +> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. > > — [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol @@ -53,7 +53,7 @@ This class of status code indicates that further action needs to be taken by the ## Client Error - 4xx -The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. +The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. HTTP_400_BAD_REQUEST HTTP_401_UNAUTHORIZED @@ -79,7 +79,7 @@ The 4xx class of status code is intended for cases in which the client seems to ## Server Error - 5xx -Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. +Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. HTTP_500_INTERNAL_SERVER_ERROR HTTP_501_NOT_IMPLEMENTED diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 8b26b3e3..37ebd55f 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -122,13 +122,13 @@ You won't typically need to override this method. > > — [Nick Coghlan][cite2] -REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed. +REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed. ## @api_view() **Signature:** `@api_view(http_method_names)` -The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: +The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: from rest_framework.decorators import api_view @@ -141,7 +141,7 @@ This view will use the default renderers, parsers, authentication classes etc sp ## API policy decorators -To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: +To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: from rest_framework.decorators import api_view, throttle_classes from rest_framework.throttling import UserRateThrottle diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index d98f37d8..2783da98 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -13,11 +13,11 @@ A `ViewSet` class is simply **a type of class-based View, that does not provide The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. -Typically, rather than exlicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. +Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. ## Example -Let's define a simple viewset that can be used to listing or retrieving all the users in the system. +Let's define a simple viewset that can be used to list or retrieve all the users in the system. class UserViewSet(viewsets.ViewSet): """ @@ -34,7 +34,7 @@ Let's define a simple viewset that can be used to listing or retrieving all the serializer = UserSerializer(user) return Response(serializer.data) -If we need to, we can bind this viewset into two seperate views, like so: +If we need to, we can bind this viewset into two separate views, like so: user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) @@ -65,7 +65,7 @@ Both of these come with a trade-off. Using regular views and URL confs is more The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below: - class UserViewSet(viewsets.VietSet): + class UserViewSet(viewsets.ViewSet): """ Example empty viewset demonstrating the standard actions that will be handled by a router class. @@ -92,7 +92,7 @@ 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` decroator 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 `@link` or `@action` decorators. The `@link` decorator will route `GET` requests, and the `@action` decorator will route `POST` requests. For example: @@ -126,6 +126,11 @@ The `@action` and `@link` decorators can additionally take extra arguments that 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: + + @action(methods=['POST', 'DELETE']) + def unset_password(self, request, pk=None): + ... --- # API Reference @@ -136,9 +141,15 @@ The `ViewSet` class inherits from `APIView`. You can use any of the standard at The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. +## GenericViewSet + +The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default. + +In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly. + ## ModelViewSet -The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the +The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`. @@ -188,17 +199,18 @@ Again, as with `ModelViewSet`, you can use any of the standard attributes and me # Custom ViewSet base classes -Any standard `View` class can be turned into a `ViewSet` class by mixing in `ViewSetMixin`. You can use this to define your own base classes. +You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way. ## Example -For example, we can create a base viewset class that provides `retrieve`, `update` and `list` operations: +To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions: + + class CreateListRetrieveViewSet(mixins.CreateMixin, + mixins.ListMixin, + mixins.RetrieveMixin, + viewsets.GenericViewSet): + pass - class RetrieveUpdateListViewSet(mixins.RetrieveModelMixin, - mixins.UpdateModelMixin, - mixins.ListModelMixin, - viewsets.ViewSetMixin, - generics.GenericAPIView): """ A viewset that provides `retrieve`, `update`, and `list` actions. @@ -207,6 +219,6 @@ For example, we can create a base viewset class that provides `retrieve`, `updat """ pass -By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API. +By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API. [cite]: http://guides.rubyonrails.org/routing.html diff --git a/docs/css/default.css b/docs/css/default.css index 998efa27..a4f05daa 100644 --- a/docs/css/default.css +++ b/docs/css/default.css @@ -103,6 +103,10 @@ pre { overflow: hidden; } +.nav-list > li > a { + padding: 2px 15px 3px; +} + /* Set the table of contents to static so it flows back into the content when viewed on tablets and smaller. */ @media (max-width: 767px) { @@ -297,4 +301,5 @@ td, th { table { border-color: white; + margin-bottom: 0.6em; } diff --git a/docs/index.md b/docs/index.md index cc960a98..0fb5706e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,10 +1,10 @@ <p class="badges"> <iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&repo=django-rest-framework&type=watch&count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe> -<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none">Tweet</a> +<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none"></a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> -<img alt="Travis build image" src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image"> +<img src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image"> </p> # Django REST framework @@ -15,7 +15,7 @@ Django REST framework is a powerful and flexible toolkit that makes it easy to b Some reasons you might want to use REST framework: -* The Web browseable API is a huge useability win for your developers. +* The Web browseable API is a huge usability win for your developers. * Authentication policies including OAuth1a and OAuth2 out of the box. * Serialization that supports both ORM and non-ORM data sources. * Customizable all the way down - just use regular function-based views if you don't need the more powerful features. @@ -32,7 +32,7 @@ There is a live example API for testing purposes, [available here][sandbox]. REST framework requires the following: * Python (2.6.5+, 2.7, 3.2, 3.3) -* Django (1.3, 1.4, 1.5) +* Django (1.3, 1.4, 1.5, 1.6) The following packages are optional: @@ -113,8 +113,8 @@ Here's our project's root `urls.py` module: # Routers provide an easy way of automatically determining the URL conf router = routers.DefaultRouter() - router.register(r'users', views.UserViewSet) - router.register(r'groups', views.GroupViewSet) + router.register(r'users', UserViewSet) + router.register(r'groups', GroupViewSet) # Wire up our API using automatic URL routing. @@ -206,7 +206,13 @@ For updates on REST framework development, you may also want to follow [the auth <a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> - + +## Security + +If you believe you’ve found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**. + +Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure. + ## License Copyright (c) 2011-2013, Tom Christie @@ -294,6 +300,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [stack-overflow]: http://stackoverflow.com/ [django-rest-framework-tag]: http://stackoverflow.com/questions/tagged/django-rest-framework [django-tag]: http://stackoverflow.com/questions/tagged/django +[security-mail]: mailto:rest-framework-security@googlegroups.com [paid-support]: http://dabapps.com/services/build/api-development/ [dabapps]: http://dabapps.com [contact-dabapps]: http://dabapps.com/contact/ diff --git a/docs/topics/2.2-announcement.md b/docs/topics/2.2-announcement.md index d7164ce4..02cac129 100644 --- a/docs/topics/2.2-announcement.md +++ b/docs/topics/2.2-announcement.md @@ -75,7 +75,7 @@ This more explicit behavior on serializing and deserializing data [makes integra The implicit to-many behavior on serializers, and the `ManyRelatedField` style classes will continue to function, but will raise a `PendingDeprecationWarning`, which can be made visible using the `-Wd` flag. -**Note**: If you need to forcibly turn off the implict "`many=True` for `__iter__` objects" behavior, you can now do so by specifying `many=False`. This will become the default (instead of the current default of `None`) once the deprecation of the implicit behavior is finalised in version 2.4. +**Note**: If you need to forcibly turn off the implicit "`many=True` for `__iter__` objects" behavior, you can now do so by specifying `many=False`. This will become the default (instead of the current default of `None`) once the deprecation of the implicit behavior is finalised in version 2.4. ### Cleaner optional relationships @@ -103,9 +103,9 @@ The `blank` keyword argument will continue to function, but will raise a `Pendin ### Simpler object-level permissions -Custom permissions classes previously used the signatute `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance. +Custom permissions classes previously used the signature `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance. -The global permissions check and object-level permissions check are now seperated into two seperate methods, which gives a cleaner, more obvious API. +The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API. * Global permission checks now use the `.has_permission(self, request, view)` signature. * Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`. diff --git a/docs/topics/2.3-announcement.md b/docs/topics/2.3-announcement.md index 6677c800..9fdebcd9 100644 --- a/docs/topics/2.3-announcement.md +++ b/docs/topics/2.3-announcement.md @@ -30,8 +30,8 @@ As an example of just how simple REST framework APIs can now be, here's an API w # Routers provide an easy way of automatically determining the URL conf router = routers.DefaultRouter() - router.register(r'users', views.UserViewSet) - router.register(r'groups', views.GroupViewSet) + router.register(r'users', UserViewSet) + router.register(r'groups', GroupViewSet) # Wire up our API using automatic URL routing. @@ -45,13 +45,13 @@ The best place to get started with ViewSets and Routers is to take a look at the ## Simpler views -This release rationalises the API and implementation of the generic views, dropping the dependancy on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with. +This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with. This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses. ## Easier Serializers -REST framework lets you be totally explict regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships. +REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships. The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class. @@ -108,7 +108,7 @@ Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continu ### Removed attributes -The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unusedand have now been entirely removed. +The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed. * context_object_name * get_context_data() @@ -173,7 +173,7 @@ For example: raise Http404 return queryset -In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-inforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views. +In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views. ## Simpler URL lookups diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md index f7d12940..4566f38b 100644 --- a/docs/topics/ajax-csrf-cors.md +++ b/docs/topics/ajax-csrf-cors.md @@ -1,6 +1,6 @@ # Working with AJAX, CSRF & CORS -> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." +> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." > > — [Jeff Atwood][cite] diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md index 8ee01824..dcba9b0a 100644 --- a/docs/topics/browsable-api.md +++ b/docs/topics/browsable-api.md @@ -1,20 +1,20 @@ # The Browsable API -> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them. +> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them. > > — [Alfred North Whitehead][cite], An Introduction to Mathematics (1911) -API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`. +API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`. ## URLs -If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose. +If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose. ## Formats -By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview]. +By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview]. ## Customizing @@ -25,15 +25,26 @@ The included browsable API template is built with [Bootstrap (2.1.1)][bootstrap] ### Theme -To replace the theme wholesale, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme. +To replace the theme wholesale, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme. {% block bootstrap_theme %} <link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css"> {% endblock %} -A suitable replacement theme can be generated using Bootstrap's [Customize Tool][bcustomize]. Also, there are pre-made themes available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. +A suitable replacement theme can be generated using Bootstrap's [Customize Tool][bcustomize]. Also, there are pre-made themes available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. + +You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style. + +Full Example + + {% extends "rest_framework/base.html" %} + + {% block bootstrap_theme %} + <link rel="stylesheet" href="/path/to/yourtheme/bootstrap.min.css' type="text/css"> + {% endblock %} + + {% block bootstrap_navbar_variant %}{% endblock %} -You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style. For more specific CSS tweaks, use the `style` block instead. @@ -46,11 +57,11 @@ All of the blocks available in the browsable API base template that can be used * `bootstrap_theme` - CSS for the Bootstrap theme * `bootstrap_navbar_variant` - CSS class for the navbar * `branding` - section of the navbar, see [Bootstrap components][bcomponentsnav] -* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block. +* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block. * `footer` - Any copyright notices or similar footer materials can go here (by default right-aligned) * `style` - CSS stylesheets for the page * `title` - title of the page -* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links. +* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links. #### Components @@ -58,7 +69,7 @@ All of the [Bootstrap components][bcomponents] are available. ##### Tooltips -The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content displayed in a tooltip on hover after a 1000ms delay. +The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content displayed in a tooltip on hover after a 1000ms delay. ### Login Template @@ -96,7 +107,7 @@ The context that's available to the template: #### Not using base.html -For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you. +For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you. [cite]: http://en.wikiquote.org/wiki/Alfred_North_Whitehead [drfreverse]: ../api-guide/reverse.md diff --git a/docs/topics/browser-enhancements.md b/docs/topics/browser-enhancements.md index ce07fe95..5a172620 100644 --- a/docs/topics/browser-enhancements.md +++ b/docs/topics/browser-enhancements.md @@ -21,7 +21,7 @@ For example, given the following form: ## HTTP header based method overriding -REST framework also supports method overriding via the semi-standard `X-HTTP-Method-Override` header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as `PATCH`. For example [Amazon Web Services ELB][aws_elb]. +REST framework also supports method overriding via the semi-standard `X-HTTP-Method-Override` header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as `PATCH`. For example [Amazon Web Services ELB][aws_elb]. To use it, make a `POST` request, setting the `X-HTTP-Method-Override` header. @@ -60,7 +60,7 @@ have any control over what is sent in the `Accept` header. ## URL based format suffixes REST framework can take `?format=json` style URL parameters, which can be a -useful shortcut for determing which content type should be returned from +useful shortcut for determining which content type should be returned from the view. This is a more concise than using the `accept` override, but it also gives diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md index 1d1fe892..123e4a8a 100644 --- a/docs/topics/contributing.md +++ b/docs/topics/contributing.md @@ -1,6 +1,6 @@ # Contributing to REST framework -> The world can only really be changed one piece at a time. The art is picking that piece. +> The world can only really be changed one piece at a time. The art is picking that piece. > > — [Tim Berners-Lee][cite] @@ -22,9 +22,9 @@ It's really helpful if you make sure you address issues to the correct channel. Some tips on good issue reporting: -* When decribing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing. +* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing. * Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue. -* If reporting a bug, then try to include a pull request with a failing test case. This'll help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one. +* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one. @@ -32,6 +32,7 @@ Some tips on good issue reporting: # Development + * git clone & PYTHONPATH * Pep8 * Recommend editor that runs pep8 diff --git a/docs/topics/credits.md b/docs/topics/credits.md index 13f673c9..bbe209c7 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -120,6 +120,25 @@ The following people have helped make REST framework great. * Jerome Chen - [chenjyw] * Andrew Hughes - [eyepulp] * Daniel Hepper - [dhepper] +* Hamish Campbell - [hamishcampbell] +* Marlon Bailey - [avinash240] +* James Summerfield - [jsummerfield] +* Andy Freeland - [rouge8] +* Craig de Stigter - [craigds] +* Pablo Recio - [pyriku] +* Brian Zambrano - [brianz] +* Òscar Vilaplana - [grimborg] +* Ryan Kaskel - [ryankask] +* Andy McKay - [andymckay] +* Matteo Suppo - [matteosuppo] +* Karol Majta - [lolek09] +* David Jones - [commonorgarden] +* Andrew Tarzwell - [atarzwell] +* Michal Dvořák - [mikee2185] +* Markus Törnqvist - [mjtorn] +* Pascal Borreli - [pborreli] +* Alex Burgel - [aburgel] +* David Medina - [copitux] Many thanks to everyone who's contributed to the project. @@ -133,7 +152,7 @@ Continuous integration testing is managed with [Travis CI][travis-ci]. The [live sandbox][sandbox] is hosted on [Heroku]. -Various inspiration taken from the [Rails], [Piston], [Tastypie] and [Dagny] projects. +Various inspiration taken from the [Rails], [Piston], [Tastypie], [Dagny] and [django-viewsets] projects. Development of REST framework 2.0 was sponsored by [DabApps]. @@ -152,6 +171,7 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [piston]: https://bitbucket.org/jespern/django-piston [tastypie]: https://github.com/toastdriven/django-tastypie [dagny]: https://github.com/zacharyvoase/dagny +[django-viewsets]: https://github.com/BertrandBordage/django-viewsets [dabapps]: http://lab.dabapps.com [sandbox]: http://restframework.herokuapp.com/ [heroku]: http://www.heroku.com/ @@ -275,3 +295,22 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [chenjyw]: https://github.com/chenjyw [eyepulp]: https://github.com/eyepulp [dhepper]: https://github.com/dhepper +[hamishcampbell]: https://github.com/hamishcampbell +[avinash240]: https://github.com/avinash240 +[jsummerfield]: https://github.com/jsummerfield +[rouge8]: https://github.com/rouge8 +[craigds]: https://github.com/craigds +[pyriku]: https://github.com/pyriku +[brianz]: https://github.com/brianz +[grimborg]: https://github.com/grimborg +[ryankask]: https://github.com/ryankask +[andymckay]: https://github.com/andymckay +[matteosuppo]: https://github.com/matteosuppo +[lolek09]: https://github.com/lolek09 +[commonorgarden]: https://github.com/commonorgarden +[atarzwell]: https://github.com/atarzwell +[mikee2185]: https://github.com/mikee2185 +[mjtorn]: https://github.com/mjtorn +[pborreli]: https://github.com/pborreli +[aburgel]: https://github.com/aburgel +[copitux]: https://github.com/copitux diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index 259aafdd..9ac51f42 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -40,6 +40,46 @@ You can determine your currently installed version using `pip freeze`: ## 2.3.x series +### 2.3.5 + +**Date**: 3rd June 2013 + +* Added `get_url` hook to `HyperlinkedIdentityField`. +* Serializer field `default` argument may be a callable. +* `@action` decorator now accepts a `methods` argument. +* Bugfix: `request.user` should be still be accessible in renderer context if authentication fails. +* Bugfix: The `lookup_field` option on `HyperlinkedIdentityField` should apply by default to the url field on the serializer. +* Bugfix: `HyperlinkedIdentityField` should continue to support `pk_url_kwarg`, `slug_url_kwarg`, `slug_field`, in a pending deprecation state. +* Bugfix: Ensure we always return 404 instead of 500 if a lookup field cannot be converted to the correct lookup type. (Eg non-numeric `AutoInteger` pk lookup) + +### 2.3.4 + +**Date**: 24th May 2013 + +* Serializer fields now support `label` and `help_text`. +* Added `UnicodeJSONRenderer`. +* `OPTIONS` requests now return metadata about fields for `POST` and `PUT` requests. +* Bugfix: `charset` now properly included in `Content-Type` of responses. +* Bugfix: Blank choice now added in browsable API on nullable relationships. +* Bugfix: Many to many relationships with `through` tables are now read-only. +* Bugfix: Serializer fields now respect model field args such as `max_length`. +* Bugfix: SlugField now performs slug validation. +* Bugfix: Lazy-translatable strings now properly serialized. +* Bugfix: Browsable API now supports bootswatch styles properly. +* Bugfix: HyperlinkedIdentityField now uses `lookup_field` kwarg. + +**Note**: Responses now correctly include an appropriate charset on the `Content-Type` header. For example: `application/json; charset=utf-8`. If you have tests that check the content type of responses, you may need to update these accordingly. + +### 2.3.3 + +**Date**: 16th May 2013 + +* Added SearchFilter +* Added OrderingFilter +* Added GenericViewSet +* Bugfix: Multiple `@action` and `@link` methods now allowed on viewsets. +* Bugfix: Fix API Root view issue with DjangoModelPermissions + ### 2.3.2 **Date**: 8th May 2013 @@ -78,14 +118,14 @@ You can determine your currently installed version using `pip freeze`: **Date**: 17th April 2013 * Loud failure when view does not return a `Response` or `HttpResponse`. -* Bugfix: Fix for Django 1.3 compatiblity. +* Bugfix: Fix for Django 1.3 compatibility. * Bugfix: Allow overridden `get_object()` to work correctly. ### 2.2.6 **Date**: 4th April 2013 -* OAuth2 authentication no longer requires unneccessary URL parameters in addition to the token. +* OAuth2 authentication no longer requires unnecessary URL parameters in addition to the token. * URL hyperlinking in browsable API now handles more cases correctly. * Long HTTP headers in browsable API are broken in multiple lines when possible. * Bugfix: Fix regression with DjangoFilterBackend not worthing correctly with single object views. @@ -197,7 +237,7 @@ The security vulnerabilities only affect APIs which use the `XMLParser` class, b * Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. * Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one -**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details. +**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details. ### 2.1.15 diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md index 309548d0..f1060d90 100644 --- a/docs/topics/rest-framework-2-announcement.md +++ b/docs/topics/rest-framework-2-announcement.md @@ -2,7 +2,7 @@ What it is, and why you should care. -> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result. +> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result. > > — [Roy Fielding][cite] @@ -22,9 +22,9 @@ This article is intended to give you a flavor of what REST framework 2 is, and w Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters… -"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1] +"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1] -"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2] +"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2] "I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3] @@ -60,7 +60,7 @@ REST framework 2 also allows you to work with both function-based and class-base ## API Design -Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independantly of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions. +Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions. ## The Browsable API @@ -70,7 +70,7 @@ Browsable Web APIs are easier to work with, visualize and debug, and generally m With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with. -There are also some functionality improvments - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions. +There are also some functionality improvements - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions. ![Browsable API][image] diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md index 43e5a8c6..b4899a36 100644 --- a/docs/topics/rest-hypermedia-hateoas.md +++ b/docs/topics/rest-hypermedia-hateoas.md @@ -1,6 +1,6 @@ # REST, Hypermedia & HATEOAS -> You keep using that word "REST". I do not think it means what you think it means. +> You keep using that word "REST". I do not think it means what you think it means. > > — Mike Amundsen, [REST fest 2012 keynote][cite]. @@ -37,8 +37,8 @@ What REST framework doesn't do is give you is machine readable hypermedia format [cite]: http://vimeo.com/channels/restfest/page:2 [dissertation]: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm [hypertext-driven]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven -[restful-web-services]: -[building-hypermedia-apis]: … +[restful-web-services]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260 +[building-hypermedia-apis]: http://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578 [designing-hypermedia-apis]: http://designinghypermediaapis.com/ [restisover]: http://blog.steveklabnik.com/posts/2012-02-23-rest-is-over [readinglist]: http://blog.steveklabnik.com/posts/2012-02-27-hypermedia-api-reading-list diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index ed54a876..bbb9b73c 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -2,13 +2,13 @@ ## Introduction -This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together. +This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together. The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead. --- -**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox]. +**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox]. --- @@ -73,7 +73,7 @@ Okay, we're ready to roll. ## Creating a model to work with -For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. +For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. from django.db import models from pygments.lexers import get_all_lexers @@ -146,6 +146,8 @@ The first thing we need to get started on our Web API is provide a way of serial 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. +Notice that we can also use various attributes that would typically be used on form fields, such as `widget=widgets.Testarea`. 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. + We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. ## Working with Serializers @@ -293,7 +295,7 @@ We'll also need a view which corresponds to an individual snippet, and can be us snippet.delete() return HttpResponse(status=204) -Finally we need to wire these views up. Create the `snippets/urls.py` file: +Finally we need to wire these views up. Create the `snippets/urls.py` file: from django.conf.urls import patterns, url diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 3a002cb0..30966a10 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -8,7 +8,7 @@ Let's introduce a couple of essential building blocks. REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.DATA` attribute, which is similar to `request.POST`, but more useful for working with Web APIs. request.POST # Only handles form data. Only works for 'POST' method. - request.DATA # Handles arbitrary data. Works any HTTP request with content. + request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. ## Response objects @@ -98,7 +98,7 @@ Notice that we're no longer explicitly tying our requests or responses to a give ## Adding optional format suffixes to our URLs -To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url]. +To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url]. Start by adding a `format` keyword argument to both of the views, like so. @@ -158,7 +158,7 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/sni ### Browsability -Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation. +Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation. Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API. diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 70cf2c54..c1b3d8f2 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -102,7 +102,7 @@ Let's take a look at how we can compose our views by using the mixin classes. def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) -We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`. +We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`. The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index f6c3efb0..393d879a 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -17,7 +17,7 @@ Add the following two fields to the model. owner = models.ForeignKey('auth.User', related_name='snippets') highlighted = models.TextField() -We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code higlighting library. +We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library. We'll need some extra imports: @@ -94,7 +94,7 @@ On **both** the `SnippetList` and `SnippetDetail` view classes, add the followin ## Updating our serializer -Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition: +Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition: owner = serializers.Field(source='owner.username') @@ -120,7 +120,7 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai ## Adding login to the Browsable API -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. +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 our URLconf once more. @@ -137,7 +137,7 @@ And, at the end of the file, add a pattern to include the login and logout views The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace. -Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earier, you'll be able to create code snippets again. +Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again. Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field. diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index cb2e092c..2e013a94 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -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 add: from rest_framework import renderers from rest_framework.response import Response diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 4b01d3e0..4ed10e82 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -1,4 +1,4 @@ -# Tutorial 6 - ViewSets & Routers +# Tutorial 6: ViewSets & Routers REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions. @@ -59,7 +59,7 @@ To see what's going on under the hood let's first explicitly create a set of vie In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views. - from snippets.resources import SnippetResource, UserResource + from snippets.views import SnippetViewSet, UserViewSet snippet_list = SnippetViewSet.as_view({ 'get': 'list', @@ -119,7 +119,7 @@ Registering the viewsets with the router is similar to providing a urlpattern. The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module. -## Trade-offs between views vs viewsets. +## Trade-offs between views vs viewsets Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf. diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 52fe3acf..f15e75c0 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -2,7 +2,43 @@ We're going to create a simple API to allow admin users to view and edit the users and groups in the system. -Create a new Django project, and start a new app called `quickstart`. Once you've set up a database and got everything synced and ready to go open up the app's directory and we'll get coding... +## Project setup + +Create a new Django project named `tutorial`, then start a new app called `quickstart`. + + # Set up a new project + django-admin.py startproject tutorial + cd tutorial + + # Create a virtualenv to isolate our package dependencies locally + virtualenv env + source env/bin/activate + + # Install Django and Django REST framework into the virtualenv + pip install django + pip install djangorestframework + + # Create a new app + python manage.py startapp quickstart + +Next you'll need to get a database set up and synced. If you just want to use SQLite for now, then you'll want to edit your `tutorial/settings.py` module to include something like this: + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': 'database.sql', + 'USER': '', + 'PASSWORD': '', + 'HOST': '', + 'PORT': '' + } + } + +The run `syncdb` like so: + + python manage.py syncdb + +Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding... ## Serializers @@ -55,7 +91,7 @@ We can easily break these down into individual views if we need to, but using vi ## URLs -Okay, now let's wire up the API URLs. On to `quickstart/urls.py`... +Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... from django.conf.urls import patterns, url, include from rest_framework import routers @@ -80,7 +116,7 @@ Finally, we're including default login and logout views for use with the browsab ## Settings -We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. +We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in `tutorial/settings.py` INSTALLED_APPS = ( ... @@ -98,6 +134,10 @@ Okay, we're done. ## Testing our API +We're now ready to test the API we've built. Let's fire up the server from the command line. + + python ./manage.py runserver + We can now access our API, both from the command-line, using tools like `curl`... bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ |
