mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-06-08 07:33:23 +03:00
Improve style, fix some typos (#8405)
* Improve style, fix some typos * Update docs/api-guide/fields.md Co-authored-by: Tom Christie <tom@tomchristie.com> Co-authored-by: Tom Christie <tom@tomchristie.com>
This commit is contained in:
parent
e354331743
commit
041b88f8bb
|
@ -201,7 +201,7 @@ If you've already created some users, you can generate tokens for all existing u
|
||||||
|
|
||||||
#### By exposing an api endpoint
|
#### By exposing an api endpoint
|
||||||
|
|
||||||
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behaviour. To use it, add the `obtain_auth_token` view to your URLconf:
|
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
|
||||||
|
|
||||||
from rest_framework.authtoken import views
|
from rest_framework.authtoken import views
|
||||||
urlpatterns += [
|
urlpatterns += [
|
||||||
|
@ -216,7 +216,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
||||||
|
|
||||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
||||||
|
|
||||||
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply to throttle you'll need to override the view class,
|
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||||
and include them using the `throttle_classes` attribute.
|
and include them using the `throttle_classes` attribute.
|
||||||
|
|
||||||
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||||
|
@ -250,7 +250,7 @@ And in your `urls.py`:
|
||||||
|
|
||||||
#### With Django admin
|
#### With Django admin
|
||||||
|
|
||||||
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||||
|
|
||||||
`your_app/admin.py`:
|
`your_app/admin.py`:
|
||||||
|
|
||||||
|
@ -289,7 +289,7 @@ If you're using an AJAX-style API with SessionAuthentication, you'll need to mak
|
||||||
|
|
||||||
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
||||||
|
|
||||||
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
|
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
|
||||||
|
|
||||||
|
|
||||||
## RemoteUserAuthentication
|
## RemoteUserAuthentication
|
||||||
|
@ -299,7 +299,7 @@ environment variable.
|
||||||
|
|
||||||
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
||||||
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
||||||
already exist. To change this and other behaviour, consult the
|
already exist. To change this and other behavior, consult the
|
||||||
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
||||||
|
|
||||||
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
||||||
|
@ -307,7 +307,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
|
||||||
* `request.user` will be a Django `User` instance.
|
* `request.user` will be a Django `User` instance.
|
||||||
* `request.auth` will be `None`.
|
* `request.auth` will be `None`.
|
||||||
|
|
||||||
Consult your web server's documentation for information about configuring an authentication method, e.g.:
|
Consult your web server's documentation for information about configuring an authentication method, for example:
|
||||||
|
|
||||||
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
||||||
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
||||||
|
@ -418,7 +418,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
||||||
|
|
||||||
## Djoser
|
## Djoser
|
||||||
|
|
||||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is ready to use REST implementation of the Django authentication system.
|
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
|
||||||
|
|
||||||
## django-rest-auth / dj-rest-auth
|
## django-rest-auth / dj-rest-auth
|
||||||
|
|
||||||
|
|
|
@ -46,7 +46,7 @@ Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-f
|
||||||
|
|
||||||
### `default`
|
### `default`
|
||||||
|
|
||||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
|
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
|
||||||
|
|
||||||
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
||||||
|
|
||||||
|
@ -85,7 +85,7 @@ When serializing fields with dotted notation, it may be necessary to provide a `
|
||||||
class CommentSerializer(serializers.Serializer):
|
class CommentSerializer(serializers.Serializer):
|
||||||
email = serializers.EmailField(source="user.email")
|
email = serializers.EmailField(source="user.email")
|
||||||
|
|
||||||
would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
||||||
|
|
||||||
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
||||||
|
|
||||||
|
@ -151,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
|
||||||
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
||||||
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
||||||
previous versions of Django, default `BooleanField` instances will be generated
|
previous versions of Django, default `BooleanField` instances will be generated
|
||||||
with a `required=False` option. If you want to control this behaviour manually,
|
with a `required=False` option. If you want to control this behavior manually,
|
||||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||||
`extra_kwargs` option to set the `required` flag.
|
`extra_kwargs` option to set the `required` flag.
|
||||||
|
|
||||||
|
@ -771,7 +771,7 @@ Here the mapping between the target and source attribute pairs (`x` and
|
||||||
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
||||||
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
||||||
|
|
||||||
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
|
Our new `DataPointSerializer` exhibits the same behavior as the custom field
|
||||||
approach.
|
approach.
|
||||||
|
|
||||||
Serializing:
|
Serializing:
|
||||||
|
|
|
@ -98,7 +98,7 @@ For example:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Note:** If the serializer_class used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
@ -177,7 +177,7 @@ This permission class ties into Django's standard `django.contrib.auth` [model p
|
||||||
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
||||||
* `DELETE` requests require the user to have the `delete` permission on the model.
|
* `DELETE` requests require the user to have the `delete` permission on the model.
|
||||||
|
|
||||||
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||||
|
|
||||||
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
||||||
|
|
||||||
|
|
|
@ -105,7 +105,7 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
|
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
|
||||||
|
|
||||||
```
|
```
|
||||||
response.data = {'results': response.data}
|
response.data = {'results': response.data}
|
||||||
|
@ -332,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
|
||||||
* Specify multiple types of HTML representation for API clients to use.
|
* Specify multiple types of HTML representation for API clients to use.
|
||||||
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
||||||
|
|
||||||
## Varying behaviour by media type
|
## Varying behavior by media type
|
||||||
|
|
||||||
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
||||||
|
|
||||||
|
|
|
@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
|
||||||
|
|
||||||
# Content negotiation
|
# Content negotiation
|
||||||
|
|
||||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
|
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
|
||||||
|
|
||||||
## .accepted_renderer
|
## .accepted_renderer
|
||||||
|
|
||||||
|
|
|
@ -594,11 +594,11 @@ The ModelSerializer class also exposes an API that you can override in order to
|
||||||
|
|
||||||
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
||||||
|
|
||||||
### `.serializer_field_mapping`
|
### `serializer_field_mapping`
|
||||||
|
|
||||||
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
||||||
|
|
||||||
### `.serializer_related_field`
|
### `serializer_related_field`
|
||||||
|
|
||||||
This property should be the serializer field class, that is used for relational fields by default.
|
This property should be the serializer field class, that is used for relational fields by default.
|
||||||
|
|
||||||
|
@ -606,13 +606,13 @@ For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
|
||||||
|
|
||||||
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
||||||
|
|
||||||
### `.serializer_url_field`
|
### `serializer_url_field`
|
||||||
|
|
||||||
The serializer field class that should be used for any `url` field on the serializer.
|
The serializer field class that should be used for any `url` field on the serializer.
|
||||||
|
|
||||||
Defaults to `serializers.HyperlinkedIdentityField`
|
Defaults to `serializers.HyperlinkedIdentityField`
|
||||||
|
|
||||||
### `.serializer_choice_field`
|
### `serializer_choice_field`
|
||||||
|
|
||||||
The serializer field class that should be used for any choice fields on the serializer.
|
The serializer field class that should be used for any choice fields on the serializer.
|
||||||
|
|
||||||
|
@ -622,13 +622,13 @@ Defaults to `serializers.ChoiceField`
|
||||||
|
|
||||||
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
||||||
|
|
||||||
### `.build_standard_field(self, field_name, model_field)`
|
### `build_standard_field(self, field_name, model_field)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a standard model field.
|
Called to generate a serializer field that maps to a standard model field.
|
||||||
|
|
||||||
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
||||||
|
|
||||||
### `.build_relational_field(self, field_name, relation_info)`
|
### `build_relational_field(self, field_name, relation_info)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a relational model field.
|
Called to generate a serializer field that maps to a relational model field.
|
||||||
|
|
||||||
|
@ -636,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r
|
||||||
|
|
||||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||||
|
|
||||||
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
|
### `build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
||||||
|
|
||||||
|
@ -646,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
|
||||||
|
|
||||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||||
|
|
||||||
### `.build_property_field(self, field_name, model_class)`
|
### `build_property_field(self, field_name, model_class)`
|
||||||
|
|
||||||
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
||||||
|
|
||||||
The default implementation returns a `ReadOnlyField` class.
|
The default implementation returns a `ReadOnlyField` class.
|
||||||
|
|
||||||
### `.build_url_field(self, field_name, model_class)`
|
### `build_url_field(self, field_name, model_class)`
|
||||||
|
|
||||||
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
||||||
|
|
||||||
### `.build_unknown_field(self, field_name, model_class)`
|
### `build_unknown_field(self, field_name, model_class)`
|
||||||
|
|
||||||
Called when the field name did not map to any model field or model property.
|
Called when the field name did not map to any model field or model property.
|
||||||
The default implementation raises an error, although subclasses may customize this behavior.
|
The default implementation raises an error, although subclasses may customize this behavior.
|
||||||
|
@ -1021,7 +1021,7 @@ Some reasons this might be useful include...
|
||||||
|
|
||||||
The signatures for these methods are as follows:
|
The signatures for these methods are as follows:
|
||||||
|
|
||||||
#### `.to_representation(self, instance)`
|
#### `to_representation(self, instance)`
|
||||||
|
|
||||||
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
||||||
|
|
||||||
|
@ -1033,7 +1033,7 @@ May be overridden in order to modify the representation style. For example:
|
||||||
ret['username'] = ret['username'].lower()
|
ret['username'] = ret['username'].lower()
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
#### ``.to_internal_value(self, data)``
|
#### ``to_internal_value(self, data)``
|
||||||
|
|
||||||
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
||||||
|
|
||||||
|
|
|
@ -208,7 +208,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
|
||||||
|
|
||||||
By default "unique together" validation enforces that all fields be
|
By default "unique together" validation enforces that all fields be
|
||||||
`required=True`. In some cases, you might want to explicit apply
|
`required=True`. In some cases, you might want to explicit apply
|
||||||
`required=False` to one of the fields, in which case the desired behaviour
|
`required=False` to one of the fields, in which case the desired behavior
|
||||||
of the validation is ambiguous.
|
of the validation is ambiguous.
|
||||||
|
|
||||||
In this case you will typically need to exclude the validator from the
|
In this case you will typically need to exclude the validator from the
|
||||||
|
|
|
@ -153,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o
|
||||||
|
|
||||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
||||||
|
|
||||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
|
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
|
||||||
|
|
||||||
@api_view(['GET', 'POST'])
|
@api_view(['GET', 'POST'])
|
||||||
def hello_world(request):
|
def hello_world(request):
|
||||||
|
|
|
@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
|
||||||
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
||||||
* `description` - the display description for the individual view of a viewset.
|
* `description` - the display description for the individual view of a viewset.
|
||||||
|
|
||||||
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||||
|
|
||||||
def get_permissions(self):
|
def get_permissions(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
|
||||||
|
|
||||||
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
||||||
|
|
||||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
|
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
|
||||||
|
|
||||||
def field_to_native(self, obj, field_name):
|
def field_to_native(self, obj, field_name):
|
||||||
"""A custom read-only field that returns the class name."""
|
"""A custom read-only field that returns the class name."""
|
||||||
|
|
|
@ -43,7 +43,7 @@ This will include two different views:
|
||||||
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
||||||
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
||||||
|
|
||||||
To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
To be compatible with this behavior, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||||
|
|
||||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||||
|
|
||||||
|
|
|
@ -398,7 +398,7 @@ then you can use the `SchemaGenerator` class directly to auto-generate the
|
||||||
`Document` instance, and to return that from a view.
|
`Document` instance, and to return that from a view.
|
||||||
|
|
||||||
This option gives you the flexibility of setting up the schema endpoint
|
This option gives you the flexibility of setting up the schema endpoint
|
||||||
with whatever behaviour you want. For example, you can apply different
|
with whatever behavior you want. For example, you can apply different
|
||||||
permission, throttling, or authentication policies to the schema endpoint.
|
permission, throttling, or authentication policies to the schema endpoint.
|
||||||
|
|
||||||
Here's an example of using `SchemaGenerator` together with a view to
|
Here's an example of using `SchemaGenerator` together with a view to
|
||||||
|
@ -650,9 +650,9 @@ def get_manual_fields(self, path, method):
|
||||||
|
|
||||||
extra_fields = []
|
extra_fields = []
|
||||||
if method == 'GET':
|
if method == 'GET':
|
||||||
extra_fields = # ... list of extra fields for GET ...
|
extra_fields = ... # list of extra fields for GET
|
||||||
if method == 'POST':
|
if method == 'POST':
|
||||||
extra_fields = # ... list of extra fields for POST ...
|
extra_fields = ... # list of extra fields for POST
|
||||||
|
|
||||||
manual_fields = super().get_manual_fields(path, method)
|
manual_fields = super().get_manual_fields(path, method)
|
||||||
return manual_fields + extra_fields
|
return manual_fields + extra_fields
|
||||||
|
|
|
@ -230,7 +230,7 @@ started.
|
||||||
In order to start working with an API, we first need a `Client` instance. The
|
In order to start working with an API, we first need a `Client` instance. The
|
||||||
client holds any configuration around which codecs and transports are supported
|
client holds any configuration around which codecs and transports are supported
|
||||||
when interacting with an API, which allows you to provide for more advanced
|
when interacting with an API, which allows you to provide for more advanced
|
||||||
kinds of behaviour.
|
kinds of behavior.
|
||||||
|
|
||||||
import coreapi
|
import coreapi
|
||||||
client = coreapi.Client()
|
client = coreapi.Client()
|
||||||
|
|
|
@ -208,7 +208,7 @@ Field templates can also use additional style properties, depending on their typ
|
||||||
The complete list of `base_template` options and their associated style options is listed below.
|
The complete list of `base_template` options and their associated style options is listed below.
|
||||||
|
|
||||||
base_template | Valid field types | Additional style options
|
base_template | Valid field types | Additional style options
|
||||||
----|----|----
|
-----------------------|-------------------------------------------------------------|-----------------------------------------------
|
||||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||||
select.html | `ChoiceField` or relational field types | hide_label
|
select.html | `ChoiceField` or relational field types | hide_label
|
||||||
|
|
|
@ -307,7 +307,7 @@ Quit out of the shell...
|
||||||
Validating models...
|
Validating models...
|
||||||
|
|
||||||
0 errors found
|
0 errors found
|
||||||
Django version 4.0,1 using settings 'tutorial.settings'
|
Django version 4.0, using settings 'tutorial.settings'
|
||||||
Starting Development server at http://127.0.0.1:8000/
|
Starting Development server at http://127.0.0.1:8000/
|
||||||
Quit the server with CONTROL-C.
|
Quit the server with CONTROL-C.
|
||||||
|
|
||||||
|
|
|
@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views.
|
||||||
|
|
||||||
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
|
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
|
||||||
|
|
||||||
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||||
|
|
||||||
## Pulling it all together
|
## Pulling it all together
|
||||||
|
|
||||||
|
|
|
@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin
|
||||||
|
|
||||||
## Using mixins
|
## Using mixins
|
||||||
|
|
||||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.
|
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
|
||||||
|
|
||||||
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
|
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
|
||||||
|
|
||||||
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
|
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user