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:
Francisco Couzo 2022-10-19 07:20:11 -03:00 committed by GitHub
parent e354331743
commit 041b88f8bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 78 additions and 78 deletions

View File

@ -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

View File

@ -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:
@ -831,7 +831,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi
## django-rest-framework-gis ## django-rest-framework-gis
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
## django-rest-framework-hstore ## django-rest-framework-hstore

View File

@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
Arguments: Arguments:
* **urlpatterns**: Required. A URL pattern list. * **urlpatterns**: Required. A URL pattern list.
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default. * **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. * **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
Example: Example:

View File

@ -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].
--- ---

View File

@ -227,7 +227,7 @@ Note that the `paginate_queryset` method may set state on the pagination instanc
## Example ## Example
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
class CustomPagination(pagination.PageNumberPagination): class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data): def get_paginated_response(self, data):

View File

@ -15,7 +15,7 @@ REST framework includes a number of built in Parser classes, that allow you to a
## How the parser is determined ## How the parser is determined
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
--- ---

View File

@ -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.

View File

@ -246,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
## HyperlinkedIdentityField ## HyperlinkedIdentityField
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
class AlbumSerializer(serializers.HyperlinkedModelSerializer): class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')

View File

@ -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}
@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende
def get_default_renderer(self, view): def get_default_renderer(self, view):
return JSONRenderer() return JSONRenderer()
## AdminRenderer ## AdminRenderer
Renders data into HTML for an admin-like display: Renders data into HTML for an admin-like display:
@ -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.

View File

@ -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

View File

@ -38,7 +38,7 @@ You should **include the request as a keyword argument** to the function, for ex
def get(self, request): def get(self, request):
year = now().year year = now().year
data = { data = {
... ...
'year-summary-url': reverse('year-summary', args=[year], request=request) 'year-summary-url': reverse('year-summary', args=[year], request=request)
} }
return Response(data) return Response(data)

View File

@ -293,7 +293,7 @@ class CustomView(APIView):
This saves you having to create a custom subclass per-view for a commonly used option. This saves you having to create a custom subclass per-view for a commonly used option.
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
the more commonly needed options do. the more commonly needed options do.
### `AutoSchema` methods ### `AutoSchema` methods
@ -301,7 +301,7 @@ the more commonly needed options do.
#### `get_components()` #### `get_components()`
Generates the OpenAPI components that describe request and response bodies, Generates the OpenAPI components that describe request and response bodies,
deriving their properties from the serializer. deriving their properties from the serializer.
Returns a dictionary mapping the component name to the generated Returns a dictionary mapping the component name to the generated
representation. By default this has just a single pair but you may override representation. By default this has just a single pair but you may override

View File

@ -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.

View File

@ -20,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
* It introduces a proper separation of concerns, making your code behavior more obvious. * It introduces a proper separation of concerns, making your code behavior more obvious.
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate. * It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance. * Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly. When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
@ -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

View File

@ -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):

View File

@ -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):
""" """
@ -247,7 +247,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes. 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()`, `.partial_update()`, and `.destroy()`. The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
#### Example #### Example

View File

@ -24,7 +24,7 @@ Notable features of this new release include:
* Support for overriding how validation errors are handled by your API. * Support for overriding how validation errors are handled by your API.
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API. * A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
* A more compact JSON output with unicode style encoding turned on by default. * A more compact JSON output with unicode style encoding turned on by default.
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release. * Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release. Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
@ -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."""

View File

@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un
### ManyToMany fields and blank=True ### ManyToMany fields and blank=True
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input. We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated. As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.

View File

@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class. * To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers]. * The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override]. * The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy. The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.

View File

@ -89,7 +89,7 @@ Name | Support | PyPI pa
---------------------------------|-------------------------------------|-------------------------------- ---------------------------------|-------------------------------------|--------------------------------
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`. [Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package. [Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package. [JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
[API Blueprint][api-blueprint] | Not yet available. | Not yet available. [API Blueprint][api-blueprint] | Not yet available. | Not yet available.
--- ---

View File

@ -89,7 +89,7 @@ for a complete listing.
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries. We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries. We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
[funding]: funding.md [funding]: funding.md
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886 [gh5886]: https://github.com/encode/django-rest-framework/issues/5886

View File

@ -124,7 +124,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
## What funding has enabled so far ## What funding has enabled so far
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues. * The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples. * The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation. * The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/). * The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
* Tom Christie, the creator of Django REST framework, working on the project full-time. * Tom Christie, the creator of Django REST framework, working on the project full-time.
@ -154,13 +154,13 @@ Sign up for a paid plan today, and help ensure that REST framework becomes a sus
&nbsp; &nbsp;
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it. > The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
> >
> &mdash; Filipe Ximenes, Vinta Software > &mdash; Filipe Ximenes, Vinta Software
&nbsp; &nbsp;
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality. > It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large. DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
> >
> &mdash; Andrew Conti, Django REST framework user > &mdash; Andrew Conti, Django REST framework user

View File

@ -205,7 +205,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions [dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
[django-url-filter]: https://github.com/miki725/django-url-filter [django-url-filter]: https://github.com/miki725/django-url-filter
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters [drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest [cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/ [drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms [django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api [djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api

View File

@ -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`:

View File

@ -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
@ -572,7 +572,7 @@ A class that deals with introspection of individual views for schema generation.
`AutoSchema` is attached to `APIView` via the `schema` attribute. `AutoSchema` is attached to `APIView` via the `schema` attribute.
The `AutoSchema` constructor takes a single keyword argument `manual_fields`. The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to **`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
the generated fields. Generated fields with a matching `name` will be overwritten. the generated fields. Generated fields with a matching `name` will be overwritten.
@ -649,10 +649,10 @@ def get_manual_fields(self, path, method):
"""Example adding per-method fields.""" """Example adding per-method fields."""
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

View File

@ -188,7 +188,7 @@ Framework.
## Support ## Support
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag. For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/). For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).

View File

@ -2,7 +2,7 @@
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability &mdash; 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 &mdash; 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."
> >
> &mdash; [Jeff Atwood][cite] > &mdash; [Jeff Atwood][cite]
## Javascript clients ## Javascript clients

View File

@ -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()

View File

@ -207,14 +207,14 @@ 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
radio.html | `ChoiceField` or relational field types | inline, hide_label radio.html | `ChoiceField` or relational field types | inline, hide_label
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
checkbox.html | `BooleanField` | hide_label checkbox.html | `BooleanField` | hide_label
fieldset.html | Nested serializer | hide_label fieldset.html | Nested serializer | hide_label
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label

View File

@ -179,7 +179,7 @@ We can also serialize querysets instead of model instances. To do so we simply
## Using ModelSerializers ## Using ModelSerializers
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise. Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes. In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
@ -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.

View File

@ -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

View File

@ -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.