mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-27 20:14:01 +03:00
Fix(docs): Add links for popular objects to inventory.
This commit is contained in:
parent
1b7dd8da67
commit
358db1a811
|
@ -111,6 +111,8 @@ If you are deploying to Apache, and using any non-session based authentication,
|
|||
|
||||
## BasicAuthentication
|
||||
|
||||
::: rest_framework.authentication.BasicAuthentication
|
||||
|
||||
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
|
||||
|
||||
If successfully authenticated, `BasicAuthentication` provides the following credentials.
|
||||
|
@ -126,6 +128,8 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
|
|||
|
||||
## TokenAuthentication
|
||||
|
||||
::: rest_framework.authentication.TokenAuthentication
|
||||
|
||||
---
|
||||
|
||||
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
|
||||
|
@ -282,6 +286,8 @@ In case you want to regenerate the token (for example if it has been compromised
|
|||
|
||||
## SessionAuthentication
|
||||
|
||||
::: rest_framework.authentication.SessionAuthentication
|
||||
|
||||
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
||||
|
||||
If successfully authenticated, `SessionAuthentication` provides the following credentials.
|
||||
|
@ -300,6 +306,8 @@ CSRF validation in REST framework works slightly differently from standard Djang
|
|||
|
||||
## RemoteUserAuthentication
|
||||
|
||||
::: rest_framework.authentication.RemoteUserAuthentication
|
||||
|
||||
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
|
||||
environment variable.
|
||||
|
||||
|
|
|
@ -97,6 +97,8 @@ Note that the exception handler will only be called for responses generated by r
|
|||
|
||||
## APIException
|
||||
|
||||
::: rest_framework.exceptions.APIException
|
||||
|
||||
**Signature:** `APIException()`
|
||||
|
||||
The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
|
||||
|
@ -145,6 +147,8 @@ dictionary of items:
|
|||
|
||||
## ParseError
|
||||
|
||||
::: rest_framework.exceptions.ParseError
|
||||
|
||||
**Signature:** `ParseError(detail=None, code=None)`
|
||||
|
||||
Raised if the request contains malformed data when accessing `request.data`.
|
||||
|
@ -153,6 +157,8 @@ By default this exception results in a response with the HTTP status code "400 B
|
|||
|
||||
## AuthenticationFailed
|
||||
|
||||
::: rest_framework.exceptions.AuthenticationFailed
|
||||
|
||||
**Signature:** `AuthenticationFailed(detail=None, code=None)`
|
||||
|
||||
Raised when an incoming request includes incorrect authentication.
|
||||
|
@ -161,6 +167,8 @@ By default this exception results in a response with the HTTP status code "401 U
|
|||
|
||||
## NotAuthenticated
|
||||
|
||||
::: rest_framework.exceptions.NotAuthenticated
|
||||
|
||||
**Signature:** `NotAuthenticated(detail=None, code=None)`
|
||||
|
||||
Raised when an unauthenticated request fails the permission checks.
|
||||
|
@ -169,6 +177,8 @@ By default this exception results in a response with the HTTP status code "401 U
|
|||
|
||||
## PermissionDenied
|
||||
|
||||
::: rest_framework.exceptions.PermissionDenied
|
||||
|
||||
**Signature:** `PermissionDenied(detail=None, code=None)`
|
||||
|
||||
Raised when an authenticated request fails the permission checks.
|
||||
|
@ -177,6 +187,8 @@ By default this exception results in a response with the HTTP status code "403 F
|
|||
|
||||
## NotFound
|
||||
|
||||
::: rest_framework.exceptions.NotFound
|
||||
|
||||
**Signature:** `NotFound(detail=None, code=None)`
|
||||
|
||||
Raised when a resource does not exist at the given URL. This exception is equivalent to the standard `Http404` Django exception.
|
||||
|
@ -185,6 +197,8 @@ By default this exception results in a response with the HTTP status code "404 N
|
|||
|
||||
## MethodNotAllowed
|
||||
|
||||
::: rest_framework.exceptions.MethodNotAllowed
|
||||
|
||||
**Signature:** `MethodNotAllowed(method, detail=None, code=None)`
|
||||
|
||||
Raised when an incoming request occurs that does not map to a handler method on the view.
|
||||
|
@ -193,6 +207,8 @@ By default this exception results in a response with the HTTP status code "405 M
|
|||
|
||||
## NotAcceptable
|
||||
|
||||
::: rest_framework.exceptions.NotAcceptable
|
||||
|
||||
**Signature:** `NotAcceptable(detail=None, code=None)`
|
||||
|
||||
Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers.
|
||||
|
@ -201,6 +217,8 @@ By default this exception results in a response with the HTTP status code "406 N
|
|||
|
||||
## UnsupportedMediaType
|
||||
|
||||
::: rest_framework.exceptions.UnsupportedMediaType
|
||||
|
||||
**Signature:** `UnsupportedMediaType(media_type, detail=None, code=None)`
|
||||
|
||||
Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`.
|
||||
|
@ -209,6 +227,8 @@ By default this exception results in a response with the HTTP status code "415 U
|
|||
|
||||
## Throttled
|
||||
|
||||
::: rest_framework.exceptions.Throttled
|
||||
|
||||
**Signature:** `Throttled(wait=None, detail=None, code=None)`
|
||||
|
||||
Raised when an incoming request fails the throttling checks.
|
||||
|
@ -217,6 +237,8 @@ By default this exception results in a response with the HTTP status code "429 T
|
|||
|
||||
## ValidationError
|
||||
|
||||
::: rest_framework.exceptions.ValidationError
|
||||
|
||||
**Signature:** `ValidationError(detail=None, code=None)`
|
||||
|
||||
The `ValidationError` exception is slightly different from the other `APIException` classes:
|
||||
|
@ -243,6 +265,8 @@ API-only application.)
|
|||
|
||||
Use these as per [Django's Customizing error views documentation][django-custom-error-views].
|
||||
|
||||
::: rest_framework.exceptions.server_error
|
||||
|
||||
## `rest_framework.exceptions.server_error`
|
||||
|
||||
Returns a response with status code `500` and `application/json` content type.
|
||||
|
@ -251,6 +275,8 @@ Set as `handler500`:
|
|||
|
||||
handler500 = 'rest_framework.exceptions.server_error'
|
||||
|
||||
::: rest_framework.exceptions.bad_request
|
||||
|
||||
## `rest_framework.exceptions.bad_request`
|
||||
|
||||
Returns a response with status code `400` and `application/json` content type.
|
||||
|
|
|
@ -142,6 +142,8 @@ For more details see the [HTML & Forms][html-and-forms] documentation.
|
|||
|
||||
## BooleanField
|
||||
|
||||
::: rest_framework.fields.BooleanField
|
||||
|
||||
A boolean representation.
|
||||
|
||||
When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.
|
||||
|
@ -165,6 +167,8 @@ Corresponds to `django.db.models.fields.BooleanField`.
|
|||
|
||||
## CharField
|
||||
|
||||
::: rest_framework.fields.CharField
|
||||
|
||||
A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`.
|
||||
|
||||
Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`.
|
||||
|
@ -180,6 +184,8 @@ The `allow_null` option is also available for string fields, although its usage
|
|||
|
||||
## EmailField
|
||||
|
||||
::: rest_framework.fields.EmailField
|
||||
|
||||
A text representation, validates the text to be a valid e-mail address.
|
||||
|
||||
Corresponds to `django.db.models.fields.EmailField`
|
||||
|
@ -188,6 +194,8 @@ Corresponds to `django.db.models.fields.EmailField`
|
|||
|
||||
## RegexField
|
||||
|
||||
::: rest_framework.fields.RegexField
|
||||
|
||||
A text representation, that validates the given value matches against a certain regular expression.
|
||||
|
||||
Corresponds to `django.forms.fields.RegexField`.
|
||||
|
@ -200,6 +208,8 @@ Uses Django's `django.core.validators.RegexValidator` for validation.
|
|||
|
||||
## SlugField
|
||||
|
||||
::: rest_framework.fields.SlugField
|
||||
|
||||
A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`.
|
||||
|
||||
Corresponds to `django.db.models.fields.SlugField`.
|
||||
|
@ -208,6 +218,8 @@ Corresponds to `django.db.models.fields.SlugField`.
|
|||
|
||||
## URLField
|
||||
|
||||
::: rest_framework.fields.URLField
|
||||
|
||||
A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http://<host>/<path>`.
|
||||
|
||||
Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
|
||||
|
@ -216,6 +228,8 @@ Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.v
|
|||
|
||||
## UUIDField
|
||||
|
||||
::: rest_framework.fields.UUIDField
|
||||
|
||||
A field that ensures the input is a valid UUID string. The `to_internal_value` method will return a `uuid.UUID` instance. On output the field will return a string in the canonical hyphenated format, for example:
|
||||
|
||||
"de305d54-75b4-431b-adb2-eb6b9e546013"
|
||||
|
@ -231,6 +245,8 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
|
|||
|
||||
## FilePathField
|
||||
|
||||
::: rest_framework.fields.FilePathField
|
||||
|
||||
A field whose choices are limited to the filenames in a certain directory on the filesystem
|
||||
|
||||
Corresponds to `django.forms.fields.FilePathField`.
|
||||
|
@ -245,6 +261,8 @@ Corresponds to `django.forms.fields.FilePathField`.
|
|||
|
||||
## IPAddressField
|
||||
|
||||
::: rest_framework.fields.IPAddressField
|
||||
|
||||
A field that ensures the input is a valid IPv4 or IPv6 string.
|
||||
|
||||
Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.GenericIPAddressField`.
|
||||
|
@ -260,6 +278,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
|
|||
|
||||
## IntegerField
|
||||
|
||||
::: rest_framework.fields.IntegerField
|
||||
|
||||
An integer representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`.
|
||||
|
@ -271,6 +291,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
|
|||
|
||||
## FloatField
|
||||
|
||||
::: rest_framework.fields.FloatField
|
||||
|
||||
A floating point representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.FloatField`.
|
||||
|
@ -282,6 +304,8 @@ Corresponds to `django.db.models.fields.FloatField`.
|
|||
|
||||
## DecimalField
|
||||
|
||||
::: rest_framework.fields.DecimalField
|
||||
|
||||
A decimal representation, represented in Python by a `Decimal` instance.
|
||||
|
||||
Corresponds to `django.db.models.fields.DecimalField`.
|
||||
|
@ -313,6 +337,8 @@ And to validate numbers up to anything less than one billion with a resolution o
|
|||
|
||||
## DateTimeField
|
||||
|
||||
::: rest_framework.fields.DateTimeField
|
||||
|
||||
A date and time representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.DateTimeField`.
|
||||
|
@ -343,6 +369,8 @@ If you want to override this behavior, you'll need to declare the `DateTimeField
|
|||
|
||||
## DateField
|
||||
|
||||
::: rest_framework.fields.DateField
|
||||
|
||||
A date representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.DateField`
|
||||
|
@ -358,6 +386,8 @@ Format strings may either be [Python strftime formats][strftime] which explicitl
|
|||
|
||||
## TimeField
|
||||
|
||||
::: rest_framework.fields.TimeField
|
||||
|
||||
A time representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.TimeField`
|
||||
|
@ -373,6 +403,8 @@ Format strings may either be [Python strftime formats][strftime] which explicitl
|
|||
|
||||
## DurationField
|
||||
|
||||
::: rest_framework.fields.DurationField
|
||||
|
||||
A Duration representation.
|
||||
Corresponds to `django.db.models.fields.DurationField`
|
||||
|
||||
|
@ -390,6 +422,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
|
|||
|
||||
## ChoiceField
|
||||
|
||||
::: rest_framework.fields.ChoiceField
|
||||
|
||||
A field that can accept a value out of a limited set of choices.
|
||||
|
||||
Used by `ModelSerializer` to automatically generate fields if the corresponding model field includes a `choices=…` argument.
|
||||
|
@ -405,6 +439,8 @@ Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, alth
|
|||
|
||||
## MultipleChoiceField
|
||||
|
||||
::: rest_framework.fields.MultipleChoiceField
|
||||
|
||||
A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_value` returns a `set` containing the selected values.
|
||||
|
||||
**Signature:** `MultipleChoiceField(choices)`
|
||||
|
@ -427,6 +463,8 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
|
|||
|
||||
## FileField
|
||||
|
||||
::: rest_framework.fields.FileField
|
||||
|
||||
A file representation. Performs Django's standard FileField validation.
|
||||
|
||||
Corresponds to `django.forms.fields.FileField`.
|
||||
|
@ -439,6 +477,8 @@ Corresponds to `django.forms.fields.FileField`.
|
|||
|
||||
## ImageField
|
||||
|
||||
::: rest_framework.fields.ImageField
|
||||
|
||||
An image representation. Validates the uploaded file content as matching a known image format.
|
||||
|
||||
Corresponds to `django.forms.fields.ImageField`.
|
||||
|
@ -457,6 +497,8 @@ Requires either the `Pillow` package or `PIL` package. The `Pillow` package is
|
|||
|
||||
## ListField
|
||||
|
||||
::: rest_framework.fields.ListField
|
||||
|
||||
A field class that validates a list of objects.
|
||||
|
||||
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
|
||||
|
@ -481,6 +523,8 @@ We can now reuse our custom `StringListField` class throughout our application,
|
|||
|
||||
## DictField
|
||||
|
||||
::: rest_framework.fields.DictField
|
||||
|
||||
A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values.
|
||||
|
||||
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
@ -499,6 +543,8 @@ You can also use the declarative style, as with `ListField`. For example:
|
|||
|
||||
## HStoreField
|
||||
|
||||
::: rest_framework.fields.HStoreField
|
||||
|
||||
A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`.
|
||||
|
||||
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
@ -510,6 +556,8 @@ Note that the child field **must** be an instance of `CharField`, as the hstore
|
|||
|
||||
## JSONField
|
||||
|
||||
::: rest_framework.fields.JSONField
|
||||
|
||||
A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.
|
||||
|
||||
**Signature**: `JSONField(binary, encoder)`
|
||||
|
@ -523,6 +571,8 @@ A field class that validates that the incoming data structure consists of valid
|
|||
|
||||
## ReadOnlyField
|
||||
|
||||
::: rest_framework.fields.ReadOnlyField
|
||||
|
||||
A field class that simply returns the value of the field without modification.
|
||||
|
||||
This field is used by default with `ModelSerializer` when including field names that relate to an attribute rather than a model field.
|
||||
|
@ -538,6 +588,8 @@ For example, if `has_expired` was a property on the `Account` model, then the fo
|
|||
|
||||
## HiddenField
|
||||
|
||||
::: rest_framework.fields.HiddenField
|
||||
|
||||
A field class that does not take a value based on user input, but instead takes its value from a default value or callable.
|
||||
|
||||
**Signature**: `HiddenField()`
|
||||
|
@ -558,6 +610,8 @@ For further examples on `HiddenField` see the [validators](validators.md) docume
|
|||
|
||||
## ModelField
|
||||
|
||||
::: rest_framework.fields.ModelField
|
||||
|
||||
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
|
||||
|
||||
This field is used by `ModelSerializer` to correspond to custom model field classes.
|
||||
|
@ -568,6 +622,8 @@ The `ModelField` class is generally intended for internal use, but can be used b
|
|||
|
||||
## SerializerMethodField
|
||||
|
||||
::: rest_framework.fields.SerializerMethodField
|
||||
|
||||
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.
|
||||
|
||||
**Signature**: `SerializerMethodField(method_name=None)`
|
||||
|
|
|
@ -190,6 +190,8 @@ It's also recommended that you read the section on [DRF integration][django-filt
|
|||
|
||||
## SearchFilter
|
||||
|
||||
::: rest_framework.filters.SearchFilter
|
||||
|
||||
The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
|
||||
|
||||
When in use, the browsable API will include a `SearchFilter` control:
|
||||
|
@ -253,6 +255,8 @@ For more details, see the [Django documentation][search-django-admin].
|
|||
|
||||
## OrderingFilter
|
||||
|
||||
::: rest_framework.filters.OrderingFilter
|
||||
|
||||
The `OrderingFilter` class supports simple query parameter controlled ordering of results.
|
||||
|
||||
![Ordering Filter](../img/ordering-filter.png)
|
||||
|
@ -312,6 +316,8 @@ The `ordering` attribute may be either a string or a list/tuple of strings.
|
|||
|
||||
# Custom generic filtering
|
||||
|
||||
::: rest_framework.filters.BaseFilterBackend
|
||||
|
||||
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
|
||||
|
||||
To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset.
|
||||
|
|
|
@ -53,6 +53,8 @@ For very simple cases you might want to pass through any class attributes using
|
|||
|
||||
## GenericAPIView
|
||||
|
||||
::: rest_framework.generics.GenericAPIView
|
||||
|
||||
This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views.
|
||||
|
||||
Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes.
|
||||
|
@ -84,6 +86,8 @@ The following attributes are used to control pagination when used with list view
|
|||
|
||||
#### `get_queryset(self)`
|
||||
|
||||
::: rest_framework.generics.GenericAPIView.get_queryset
|
||||
|
||||
Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute.
|
||||
|
||||
This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests.
|
||||
|
@ -104,6 +108,8 @@ For example:
|
|||
|
||||
#### `get_object(self)`
|
||||
|
||||
::: rest_framework.generics.GenericAPIView.get_object
|
||||
|
||||
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
|
||||
|
||||
May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
|
||||
|
@ -124,6 +130,8 @@ Note that if your API doesn't include any object level permissions, you may opti
|
|||
|
||||
#### `filter_queryset(self, queryset)`
|
||||
|
||||
::: rest_framework.generics.GenericAPIView.filter_queryset
|
||||
|
||||
Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
|
||||
|
||||
For example:
|
||||
|
@ -143,6 +151,8 @@ For example:
|
|||
|
||||
#### `get_serializer_class(self)`
|
||||
|
||||
::: rest_framework.generics.GenericAPIView.get_serializer_class
|
||||
|
||||
Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute.
|
||||
|
||||
May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.
|
||||
|
@ -201,12 +211,16 @@ The mixin classes can be imported from `rest_framework.mixins`.
|
|||
|
||||
## ListModelMixin
|
||||
|
||||
::: rest_framework.mixins.ListModelMixin
|
||||
|
||||
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
||||
|
||||
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
|
||||
|
||||
## CreateModelMixin
|
||||
|
||||
::: rest_framework.mixins.CreateModelMixin
|
||||
|
||||
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
||||
|
||||
If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
|
||||
|
@ -215,12 +229,16 @@ If the request data provided for creating the object was invalid, a `400 Bad Req
|
|||
|
||||
## RetrieveModelMixin
|
||||
|
||||
::: rest_framework.mixins.RetrieveModelMixin
|
||||
|
||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
||||
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise, it will return a `404 Not Found`.
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
::: rest_framework.mixins.UpdateModelMixin
|
||||
|
||||
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
|
||||
|
||||
Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
|
||||
|
@ -231,6 +249,8 @@ If the request data provided for updating the object was invalid, a `400 Bad Req
|
|||
|
||||
## DestroyModelMixin
|
||||
|
||||
::: rest_framework.mixins.DestroyModelMixin
|
||||
|
||||
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
|
||||
|
||||
If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
|
||||
|
@ -245,6 +265,8 @@ The view classes can be imported from `rest_framework.generics`.
|
|||
|
||||
## CreateAPIView
|
||||
|
||||
::: rest_framework.generics.CreateAPIView
|
||||
|
||||
Used for **create-only** endpoints.
|
||||
|
||||
Provides a `post` method handler.
|
||||
|
@ -253,6 +275,8 @@ Extends: [GenericAPIView], [CreateModelMixin]
|
|||
|
||||
## ListAPIView
|
||||
|
||||
::: rest_framework.generics.ListAPIView
|
||||
|
||||
Used for **read-only** endpoints to represent a **collection of model instances**.
|
||||
|
||||
Provides a `get` method handler.
|
||||
|
@ -261,6 +285,8 @@ Extends: [GenericAPIView], [ListModelMixin]
|
|||
|
||||
## RetrieveAPIView
|
||||
|
||||
::: rest_framework.generics.RetrieveAPIView
|
||||
|
||||
Used for **read-only** endpoints to represent a **single model instance**.
|
||||
|
||||
Provides a `get` method handler.
|
||||
|
@ -269,6 +295,8 @@ Extends: [GenericAPIView], [RetrieveModelMixin]
|
|||
|
||||
## DestroyAPIView
|
||||
|
||||
::: rest_framework.generics.DestroyAPIView
|
||||
|
||||
Used for **delete-only** endpoints for a **single model instance**.
|
||||
|
||||
Provides a `delete` method handler.
|
||||
|
@ -277,6 +305,8 @@ Extends: [GenericAPIView], [DestroyModelMixin]
|
|||
|
||||
## UpdateAPIView
|
||||
|
||||
::: rest_framework.generics.UpdateAPIView
|
||||
|
||||
Used for **update-only** endpoints for a **single model instance**.
|
||||
|
||||
Provides `put` and `patch` method handlers.
|
||||
|
@ -285,6 +315,8 @@ Extends: [GenericAPIView], [UpdateModelMixin]
|
|||
|
||||
## ListCreateAPIView
|
||||
|
||||
::: rest_framework.generics.ListCreateAPIView
|
||||
|
||||
Used for **read-write** endpoints to represent a **collection of model instances**.
|
||||
|
||||
Provides `get` and `post` method handlers.
|
||||
|
@ -293,6 +325,8 @@ Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin]
|
|||
|
||||
## RetrieveUpdateAPIView
|
||||
|
||||
::: rest_framework.generics.RetrieveUpdateAPIView
|
||||
|
||||
Used for **read or update** endpoints to represent a **single model instance**.
|
||||
|
||||
Provides `get`, `put` and `patch` method handlers.
|
||||
|
@ -301,6 +335,8 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin]
|
|||
|
||||
## RetrieveDestroyAPIView
|
||||
|
||||
::: rest_framework.generics.RetrieveDestroyAPIView
|
||||
|
||||
Used for **read or delete** endpoints to represent a **single model instance**.
|
||||
|
||||
Provides `get` and `delete` method handlers.
|
||||
|
@ -309,6 +345,8 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin]
|
|||
|
||||
## RetrieveUpdateDestroyAPIView
|
||||
|
||||
::: rest_framework.generics.RetrieveUpdateDestroyAPIView
|
||||
|
||||
Used for **read-write-delete** endpoints to represent a **single model instance**.
|
||||
|
||||
Provides `get`, `put`, `patch` and `delete` method handlers.
|
||||
|
|
|
@ -68,6 +68,8 @@ Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key.
|
|||
|
||||
## PageNumberPagination
|
||||
|
||||
::: rest_framework.pagination.PageNumberPagination
|
||||
|
||||
This pagination style accepts a single number page number in the request query parameters.
|
||||
|
||||
**Request**:
|
||||
|
@ -115,6 +117,8 @@ To set these attributes you should override the `PageNumberPagination` class, an
|
|||
|
||||
## LimitOffsetPagination
|
||||
|
||||
::: rest_framework.pagination.LimitOffsetPagination
|
||||
|
||||
This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
|
||||
"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.
|
||||
|
||||
|
@ -162,6 +166,8 @@ To set these attributes you should override the `LimitOffsetPagination` class, a
|
|||
|
||||
## CursorPagination
|
||||
|
||||
::: rest_framework.pagination.CursorPagination
|
||||
|
||||
The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions.
|
||||
|
||||
Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against.
|
||||
|
@ -218,6 +224,8 @@ To set these attributes you should override the `CursorPagination` class, and th
|
|||
|
||||
# Custom pagination styles
|
||||
|
||||
::: rest_framework.pagination.BasePagination
|
||||
|
||||
To create a custom pagination serializer class, you should inherit the subclass `pagination.BasePagination`, override the `paginate_queryset(self, queryset, request, view=None)`, and `get_paginated_response(self, data)` methods:
|
||||
|
||||
* The `paginate_queryset` method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.
|
||||
|
|
|
@ -73,12 +73,16 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
|
||||
## JSONParser
|
||||
|
||||
::: rest_framework.parsers.JSONParser
|
||||
|
||||
Parses `JSON` request content. `request.data` will be populated with a dictionary of data.
|
||||
|
||||
**.media_type**: `application/json`
|
||||
|
||||
## FormParser
|
||||
|
||||
::: rest_framework.parsers.FormParser
|
||||
|
||||
Parses HTML form content. `request.data` will be populated with a `QueryDict` of data.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
@ -87,6 +91,8 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
|
|||
|
||||
## MultiPartParser
|
||||
|
||||
::: rest_framework.parsers.MultiPartParser
|
||||
|
||||
Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
@ -95,6 +101,8 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
|
|||
|
||||
## FileUploadParser
|
||||
|
||||
::: rest_framework.parsers.FileUploadParser
|
||||
|
||||
Parses raw file upload content. The `request.data` property will be a dictionary with a single key `'file'` containing the uploaded file.
|
||||
|
||||
If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename.
|
||||
|
@ -132,6 +140,8 @@ If it is called without a `filename` URL keyword argument, then the client must
|
|||
|
||||
# Custom parsers
|
||||
|
||||
::: rest_framework.parsers.BaseParser
|
||||
|
||||
To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method.
|
||||
|
||||
The method should return the data that will be used to populate the `request.data` property.
|
||||
|
|
|
@ -147,30 +147,40 @@ __Note:__ it supports & (and), | (or) and ~ (not).
|
|||
|
||||
## AllowAny
|
||||
|
||||
::: rest_framework.permissions.AllowAny
|
||||
|
||||
The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**.
|
||||
|
||||
This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.
|
||||
|
||||
## IsAuthenticated
|
||||
|
||||
::: rest_framework.permissions.IsAuthenticated
|
||||
|
||||
The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise.
|
||||
|
||||
This permission is suitable if you want your API to only be accessible to registered users.
|
||||
|
||||
## IsAdminUser
|
||||
|
||||
::: rest_framework.permissions.IsAdminUser
|
||||
|
||||
The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed.
|
||||
|
||||
This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.
|
||||
|
||||
## IsAuthenticatedOrReadOnly
|
||||
|
||||
::: rest_framework.permissions.IsAuthenticatedOrReadOnly
|
||||
|
||||
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthenticated users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
|
||||
|
||||
This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
|
||||
|
||||
## DjangoModelPermissions
|
||||
|
||||
::: rest_framework.permissions.DjangoModelPermissions
|
||||
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
|
||||
|
||||
* `POST` requests require the user to have the `add` permission on the model.
|
||||
|
@ -183,6 +193,8 @@ To use custom model permissions, override `DjangoModelPermissions` and set the `
|
|||
|
||||
## DjangoModelPermissionsOrAnonReadOnly
|
||||
|
||||
::: rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly
|
||||
|
||||
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
|
||||
|
||||
## DjangoObjectPermissions
|
||||
|
@ -207,6 +219,8 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid
|
|||
|
||||
# Custom permissions
|
||||
|
||||
::: rest_framework.permissions.BasePermission
|
||||
|
||||
To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods:
|
||||
|
||||
* `.has_permission(self, request, view)`
|
||||
|
|
|
@ -85,6 +85,8 @@ In order to explain the various types of relational fields, we'll use a couple o
|
|||
|
||||
## StringRelatedField
|
||||
|
||||
::: rest_framework.relations.StringRelatedField
|
||||
|
||||
`StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
|
||||
|
||||
For example, the following serializer:
|
||||
|
@ -117,6 +119,8 @@ This field is read only.
|
|||
|
||||
## PrimaryKeyRelatedField
|
||||
|
||||
::: rest_framework.relations.PrimaryKeyRelatedField
|
||||
|
||||
`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
|
||||
|
||||
For example, the following serializer:
|
||||
|
@ -153,6 +157,8 @@ By default this field is read-write, although you can change this behavior using
|
|||
|
||||
## HyperlinkedRelatedField
|
||||
|
||||
::: rest_framework.relations.HyperlinkedRelatedField
|
||||
|
||||
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
|
||||
|
||||
For example, the following serializer:
|
||||
|
@ -205,6 +211,8 @@ If you require more complex hyperlinked representation you'll need to customize
|
|||
|
||||
## SlugRelatedField
|
||||
|
||||
::: rest_framework.relations.SlugRelatedField
|
||||
|
||||
`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
|
||||
|
||||
For example, the following serializer:
|
||||
|
@ -246,6 +254,8 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
|
|||
|
||||
## HyperlinkedIdentityField
|
||||
|
||||
::: rest_framework.relations.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:
|
||||
|
||||
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||
|
@ -362,6 +372,8 @@ By default nested serializers are read-only. If you want to support write-operat
|
|||
|
||||
# Custom relational fields
|
||||
|
||||
::: rest_framework.relations.RelatedField
|
||||
|
||||
In rare cases where none of the existing relational styles fit the representation you need,
|
||||
you can implement a completely custom relational field, that describes exactly how the
|
||||
output representation should be generated from the model instance.
|
||||
|
|
|
@ -75,6 +75,8 @@ If your API includes views that can serve both regular webpages and API response
|
|||
|
||||
## JSONRenderer
|
||||
|
||||
::: rest_framework.renderers.JSONRenderer
|
||||
|
||||
Renders the request data into `JSON`, using utf-8 encoding.
|
||||
|
||||
Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:
|
||||
|
@ -98,6 +100,8 @@ The default JSON encoding style can be altered using the `UNICODE_JSON` and `COM
|
|||
|
||||
## TemplateHTMLRenderer
|
||||
|
||||
::: rest_framework.renderers.TemplateHTMLRenderer
|
||||
|
||||
Renders data to HTML, using Django's standard template rendering.
|
||||
Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`.
|
||||
|
||||
|
@ -148,6 +152,8 @@ See also: `StaticHTMLRenderer`
|
|||
|
||||
## StaticHTMLRenderer
|
||||
|
||||
::: rest_framework.renderers.StaticHTMLRenderer
|
||||
|
||||
A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.
|
||||
|
||||
An example of a view that uses `StaticHTMLRenderer`:
|
||||
|
@ -170,6 +176,8 @@ See also: `TemplateHTMLRenderer`
|
|||
|
||||
## BrowsableAPIRenderer
|
||||
|
||||
::: rest_framework.renderers.BrowsableAPIRenderer
|
||||
|
||||
Renders data into HTML for the Browsable API:
|
||||
|
||||
![The BrowsableAPIRenderer](../img/quickstart.png)
|
||||
|
@ -194,6 +202,8 @@ By default the response content will be rendered with the highest priority rende
|
|||
|
||||
## AdminRenderer
|
||||
|
||||
::: rest_framework.renderers.AdminRenderer
|
||||
|
||||
Renders data into HTML for an admin-like display:
|
||||
|
||||
![The AdminRender view](../img/admin.png)
|
||||
|
@ -221,6 +231,8 @@ Note that views that have nested or list serializers for their input won't work
|
|||
|
||||
## HTMLFormRenderer
|
||||
|
||||
::: rest_framework.renderers.HTMLFormRenderer
|
||||
|
||||
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `<form>` tags, a hidden CSRF input or any submit buttons.
|
||||
|
||||
This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the `render_form` template tag.
|
||||
|
@ -245,6 +257,8 @@ For more information see the [HTML & Forms][html-and-forms] documentation.
|
|||
|
||||
## MultiPartRenderer
|
||||
|
||||
::: rest_framework.renderers.MultiPartRenderer
|
||||
|
||||
This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing].
|
||||
|
||||
**.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg`
|
||||
|
@ -257,6 +271,8 @@ This renderer is used for rendering HTML multipart form data. **It is not suita
|
|||
|
||||
# Custom renderers
|
||||
|
||||
::: rest_framework.renderers.BaseRenderer
|
||||
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, accepted_media_type=None, renderer_context=None)` method.
|
||||
|
||||
The method should return a bytestring, which will be used as the body of the HTTP response.
|
||||
|
|
|
@ -5,6 +5,8 @@ source:
|
|||
|
||||
# Requests
|
||||
|
||||
::: rest_framework.request.Request
|
||||
|
||||
> If you're doing REST-based web service stuff ... you should ignore request.POST.
|
||||
>
|
||||
> — Malcom Tredinnick, [Django developers group][cite]
|
||||
|
@ -15,6 +17,7 @@ REST framework's `Request` class extends the standard `HttpRequest`, adding supp
|
|||
|
||||
# Request parsing
|
||||
|
||||
|
||||
REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.
|
||||
|
||||
## .data
|
||||
|
|
|
@ -21,8 +21,11 @@ Unless you want to heavily customize REST framework for some reason, you should
|
|||
|
||||
# Creating responses
|
||||
|
||||
|
||||
## Response()
|
||||
|
||||
::: rest_framework.response.Response
|
||||
|
||||
**Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)`
|
||||
|
||||
Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.
|
||||
|
|
|
@ -24,6 +24,8 @@ There's no requirement for you to use them, but if you do then the self-describi
|
|||
|
||||
## reverse
|
||||
|
||||
::: rest_framework.reverse.reverse
|
||||
|
||||
**Signature:** `reverse(viewname, *args, **kwargs)`
|
||||
|
||||
Has the same behavior as [`django.urls.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
|
@ -45,6 +47,8 @@ You should **include the request as a keyword argument** to the function, for ex
|
|||
|
||||
## reverse_lazy
|
||||
|
||||
::: rest_framework.reverse.reverse_lazy
|
||||
|
||||
**Signature:** `reverse_lazy(viewname, *args, **kwargs)`
|
||||
|
||||
Has the same behavior as [`django.urls.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
|
|
|
@ -164,6 +164,8 @@ Note that path converters will be used on all URLs registered in the router, inc
|
|||
|
||||
## SimpleRouter
|
||||
|
||||
::: rest_framework.routers.SimpleRouter
|
||||
|
||||
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@action` decorator.
|
||||
|
||||
<table border=1>
|
||||
|
@ -187,6 +189,8 @@ Trailing slashes are conventional in Django, but are not used by default in some
|
|||
|
||||
## DefaultRouter
|
||||
|
||||
::: rest_framework.routers.DefaultRouter
|
||||
|
||||
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
|
||||
|
||||
<table border=1>
|
||||
|
@ -315,6 +319,8 @@ For another example of setting the `.routes` attribute, see the source code for
|
|||
|
||||
## Advanced custom routers
|
||||
|
||||
::: rest_framework.routers.BaseRouter
|
||||
|
||||
If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
|
||||
|
||||
You may also want to override the `get_default_basename(self, viewset)` method, or else always explicitly set the `basename` argument when registering your viewsets with the router.
|
||||
|
|
|
@ -17,6 +17,8 @@ The serializers in REST framework work very similarly to Django's `Form` and `Mo
|
|||
|
||||
## Declaring Serializers
|
||||
|
||||
::: rest_framework.serializers.Serializer
|
||||
|
||||
Let's start by creating a simple object we can use for example purposes:
|
||||
|
||||
from datetime import datetime
|
||||
|
@ -149,6 +151,8 @@ Note that in the case above we're now having to access the serializer `.validate
|
|||
|
||||
## Validation
|
||||
|
||||
::: rest_framework.serializers.Serializer.is_valid
|
||||
|
||||
When deserializing data, you always need to call `is_valid()` before attempting to access the validated data, or save an object instance. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example:
|
||||
|
||||
serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
|
||||
|
@ -428,6 +432,8 @@ The context dictionary can be used within any serializer field logic, such as a
|
|||
|
||||
# ModelSerializer
|
||||
|
||||
::: rest_framework.serializers.ModelSerializer
|
||||
|
||||
Often you'll want serializer classes that map closely to Django model definitions.
|
||||
|
||||
The `ModelSerializer` class provides a shortcut that lets you automatically create a `Serializer` class with fields that correspond to the Model fields.
|
||||
|
@ -665,6 +671,8 @@ The default implementation raises an error, although subclasses may customize th
|
|||
|
||||
# HyperlinkedModelSerializer
|
||||
|
||||
::: rest_framework.serializers.HyperlinkedModelSerializer
|
||||
|
||||
The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys.
|
||||
|
||||
By default the serializer will include a `url` field instead of a primary key field.
|
||||
|
@ -746,6 +754,8 @@ The name of the URL field defaults to 'url'. You can override this globally, by
|
|||
|
||||
# ListSerializer
|
||||
|
||||
::: rest_framework.serializers.ListSerializer
|
||||
|
||||
The `ListSerializer` class provides the behavior for serializing and validating multiple objects at once. You won't *typically* need to use `ListSerializer` directly, but should instead simply pass `many=True` when instantiating a serializer.
|
||||
|
||||
When a serializer is instantiated and `many=True` is passed, a `ListSerializer` instance will be created. The serializer class then becomes a child of the parent `ListSerializer`
|
||||
|
@ -864,6 +874,8 @@ Occasionally you might need to explicitly specify how the child and parent class
|
|||
|
||||
# BaseSerializer
|
||||
|
||||
::: rest_framework.serializers.BaseSerializer
|
||||
|
||||
`BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles.
|
||||
|
||||
This class implements the same basic API as the `Serializer` class:
|
||||
|
|
|
@ -118,6 +118,8 @@ If your project relies on guaranteeing the number of requests during concurrent
|
|||
|
||||
## AnonRateThrottle
|
||||
|
||||
::: rest_framework.throttling.AnonRateThrottle
|
||||
|
||||
The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
|
||||
|
||||
The allowed request rate is determined from one of the following (in order of preference).
|
||||
|
@ -129,6 +131,8 @@ The allowed request rate is determined from one of the following (in order of pr
|
|||
|
||||
## UserRateThrottle
|
||||
|
||||
::: rest_framework.throttling.UserRateThrottle
|
||||
|
||||
The `UserRateThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
|
||||
|
||||
The allowed request rate is determined from one of the following (in order of preference).
|
||||
|
@ -163,6 +167,8 @@ For example, multiple user throttle rates could be implemented by using the foll
|
|||
|
||||
## ScopedRateThrottle
|
||||
|
||||
::: rest_framework.throttling.ScopedRateThrottle
|
||||
|
||||
The `ScopedRateThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
|
||||
|
||||
The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope".
|
||||
|
@ -199,6 +205,8 @@ User requests to either `ContactListView` or `ContactDetailView` would be restri
|
|||
|
||||
# Custom throttles
|
||||
|
||||
::: rest_framework.throttling.BaseThrottle
|
||||
|
||||
To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
|
||||
|
||||
Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`.
|
||||
|
|
|
@ -59,6 +59,8 @@ Because of this more explicit style REST framework includes a few validator clas
|
|||
|
||||
## UniqueValidator
|
||||
|
||||
::: rest_framework.validators.UniqueValidator
|
||||
|
||||
This validator can be used to enforce the `unique=True` constraint on model fields.
|
||||
It takes a single required argument, and an optional `messages` argument:
|
||||
|
||||
|
@ -75,7 +77,9 @@ This validator should be applied to *serializer fields*, like so:
|
|||
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
|
||||
)
|
||||
|
||||
## UniqueTogetherValidator
|
||||
## UniqueTogetherValidator
|
||||
|
||||
::: rest_framework.validators.UniqueTogetherValidator
|
||||
|
||||
This validator can be used to enforce `unique_together` constraints on model instances.
|
||||
It has two required arguments, and a single optional `messages` argument:
|
||||
|
@ -109,10 +113,16 @@ The validator should be applied to *serializer classes*, like so:
|
|||
|
||||
## UniqueForDateValidator
|
||||
|
||||
::: rest_framework.validators.UniqueForDateValidator
|
||||
|
||||
## UniqueForMonthValidator
|
||||
|
||||
::: rest_framework.validators.UniqueForMonthValidator
|
||||
|
||||
## UniqueForYearValidator
|
||||
|
||||
::: rest_framework.validators.UniqueForYearValidator
|
||||
|
||||
These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments:
|
||||
|
||||
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
|
||||
|
@ -181,6 +191,9 @@ REST framework includes a couple of defaults that may be useful in this context.
|
|||
|
||||
#### CurrentUserDefault
|
||||
|
||||
::: rest_framework.fields.CurrentUserDefault
|
||||
::: rest_framework.serializers.CurrentUserDefault
|
||||
|
||||
A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
|
||||
|
||||
owner = serializers.HiddenField(
|
||||
|
@ -189,6 +202,9 @@ A default class that can be used to represent the current user. In order to use
|
|||
|
||||
#### CreateOnlyDefault
|
||||
|
||||
::: rest_framework.fields.CreateOnlyDefault
|
||||
::: rest_framework.serializers.CreateOnlyDefault
|
||||
|
||||
A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
|
||||
|
||||
It takes a single argument, which is the default value or callable that should be used during create operations.
|
||||
|
|
|
@ -94,7 +94,9 @@ You can also set your versioning class plus those three values on a per-view or
|
|||
|
||||
# API Reference
|
||||
|
||||
## AcceptHeaderVersioning
|
||||
## AcceptHeaderVersioning
|
||||
|
||||
::: rest_framework.versioning.AcceptHeaderVersioning
|
||||
|
||||
This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type.
|
||||
|
||||
|
@ -123,6 +125,8 @@ Your client requests would now look like this:
|
|||
|
||||
## URLPathVersioning
|
||||
|
||||
::: rest_framework.versioning.URLPathVersioning
|
||||
|
||||
This scheme requires the client to specify the version as part of the URL path.
|
||||
|
||||
GET /v1/bookings/ HTTP/1.1
|
||||
|
@ -146,6 +150,8 @@ Your URL conf must include a pattern that matches the version with a `'version'`
|
|||
|
||||
## NamespaceVersioning
|
||||
|
||||
::: rest_framework.versioning.NamespaceVersioning
|
||||
|
||||
To the client, this scheme is the same as `URLPathVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
|
||||
|
||||
GET /v1/something/ HTTP/1.1
|
||||
|
@ -172,6 +178,8 @@ Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just ne
|
|||
|
||||
## HostNameVersioning
|
||||
|
||||
::: rest_framework.versioning.HostNameVersioning
|
||||
|
||||
The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
|
||||
|
||||
For example the following is an HTTP request to the `http://v1.example.com/bookings/` URL:
|
||||
|
@ -192,6 +200,8 @@ Hostname based versioning can be particularly useful if you have requirements to
|
|||
|
||||
## QueryParameterVersioning
|
||||
|
||||
::: rest_framework.versioning.QueryParameterVersioning
|
||||
|
||||
This scheme is a simple style that includes the version as a query parameter in the URL. For example:
|
||||
|
||||
GET /something/?version=0.1 HTTP/1.1
|
||||
|
@ -202,6 +212,8 @@ This scheme is a simple style that includes the version as a query parameter in
|
|||
|
||||
# Custom versioning schemes
|
||||
|
||||
::: rest_framework.versioning.BaseVersioning
|
||||
|
||||
To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method.
|
||||
|
||||
## Example
|
||||
|
|
|
@ -12,6 +12,8 @@ source:
|
|||
|
||||
REST framework provides an `APIView` class, which subclasses Django's `View` class.
|
||||
|
||||
::: rest_framework.views.APIView
|
||||
|
||||
`APIView` classes are different from regular `View` classes in the following ways:
|
||||
|
||||
* Requests passed to the handler methods will be REST framework's `Request` instances, not Django's `HttpRequest` instances.
|
||||
|
@ -58,51 +60,87 @@ The following attributes control the pluggable aspects of API views.
|
|||
|
||||
### .renderer_classes
|
||||
|
||||
::: rest_framework.views.APIView.renderer_classes
|
||||
|
||||
### .parser_classes
|
||||
|
||||
::: rest_framework.views.APIView.parser_classes
|
||||
|
||||
### .authentication_classes
|
||||
|
||||
::: rest_framework.views.APIView.authentication_classes
|
||||
|
||||
### .throttle_classes
|
||||
|
||||
::: rest_framework.views.APIView.throttle_classes
|
||||
|
||||
### .permission_classes
|
||||
|
||||
::: rest_framework.views.APIView.permission_classes
|
||||
|
||||
### .content_negotiation_class
|
||||
|
||||
::: rest_framework.views.APIView.content_negotiation_class
|
||||
|
||||
## API policy instantiation methods
|
||||
|
||||
The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
|
||||
|
||||
### .get_renderers(self)
|
||||
|
||||
::: rest_framework.views.APIView.get_renderers
|
||||
|
||||
### .get_parsers(self)
|
||||
|
||||
::: rest_framework.views.APIView.get_parsers
|
||||
|
||||
### .get_authenticators(self)
|
||||
|
||||
::: rest_framework.views.APIView.get_authenticators
|
||||
|
||||
### .get_throttles(self)
|
||||
|
||||
::: rest_framework.views.APIView.get_throttles
|
||||
|
||||
### .get_permissions(self)
|
||||
|
||||
::: rest_framework.views.APIView.get_permissions
|
||||
|
||||
### .get_content_negotiator(self)
|
||||
|
||||
::: rest_framework.views.APIView.get_content_negotiator
|
||||
|
||||
### .get_exception_handler(self)
|
||||
|
||||
::: rest_framework.views.APIView.get_exception_handler
|
||||
|
||||
## API policy implementation methods
|
||||
|
||||
The following methods are called before dispatching to the handler method.
|
||||
|
||||
### .check_permissions(self, request)
|
||||
|
||||
::: rest_framework.views.APIView.check_permissions
|
||||
|
||||
### .check_throttles(self, request)
|
||||
|
||||
::: rest_framework.views.APIView.check_throttles
|
||||
|
||||
### .perform_content_negotiation(self, request, force=False)
|
||||
|
||||
::: rest_framework.views.APIView.perform_content_negotiation
|
||||
|
||||
## Dispatch methods
|
||||
|
||||
::: rest_framework.views.APIView.dispatch
|
||||
|
||||
The following methods are called directly by the view's `.dispatch()` method.
|
||||
These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()`, `patch()` and `.delete()`.
|
||||
|
||||
### .initial(self, request, \*args, **kwargs)
|
||||
|
||||
::: rest_framework.views.APIView.initial
|
||||
|
||||
Performs any actions that need to occur before the handler method gets called.
|
||||
This method is used to enforce permissions and throttling, and perform content negotiation.
|
||||
|
||||
|
@ -110,6 +148,8 @@ You won't typically need to override this method.
|
|||
|
||||
### .handle_exception(self, exc)
|
||||
|
||||
::: rest_framework.views.APIView.handle_exception
|
||||
|
||||
Any exception thrown by the handler method will be passed to this method, which either returns a `Response` instance, or re-raises the exception.
|
||||
|
||||
The default implementation handles any subclass of `rest_framework.exceptions.APIException`, as well as Django's `Http404` and `PermissionDenied` exceptions, and returns an appropriate error response.
|
||||
|
@ -118,12 +158,16 @@ If you need to customize the error responses your API returns you should subclas
|
|||
|
||||
### .initialize_request(self, request, \*args, **kwargs)
|
||||
|
||||
::: rest_framework.views.APIView.initialize_request
|
||||
|
||||
Ensures that the request object that is passed to the handler method is an instance of `Request`, rather than the usual Django `HttpRequest`.
|
||||
|
||||
You won't typically need to override this method.
|
||||
|
||||
### .finalize_response(self, request, response, \*args, **kwargs)
|
||||
|
||||
::: rest_framework.views.APIView.finalize_response
|
||||
|
||||
Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.
|
||||
|
||||
You won't typically need to override this method.
|
||||
|
@ -140,6 +184,8 @@ REST framework also allows you to work with regular function based views. It pr
|
|||
|
||||
## @api_view()
|
||||
|
||||
::: rest_framework.decorators.api_view
|
||||
|
||||
**Signature:** `@api_view(http_method_names=['GET'])`
|
||||
|
||||
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
|
||||
|
@ -192,6 +238,8 @@ Each of these decorators takes a single argument which must be a list or tuple o
|
|||
|
||||
## View schema decorator
|
||||
|
||||
::: rest_framework.decorators.schema
|
||||
|
||||
To override the default schema generation for function based views you may use
|
||||
the `@schema` decorator. This must come *after* (below) the `@api_view`
|
||||
decorator. For example:
|
||||
|
|
|
@ -9,6 +9,7 @@ source:
|
|||
>
|
||||
> — [Ruby on Rails Documentation][cite]
|
||||
|
||||
::: rest_framework.viewsets.ViewSet
|
||||
|
||||
Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
|
||||
|
||||
|
@ -130,6 +131,8 @@ You may inspect these attributes to adjust behavior based on the current action.
|
|||
|
||||
## Marking extra actions for routing
|
||||
|
||||
::: rest_framework.decorators.action
|
||||
|
||||
If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns.
|
||||
|
||||
A more complete example of extra actions:
|
||||
|
@ -247,12 +250,16 @@ The `ViewSet` class does not provide any implementations of actions. In order t
|
|||
|
||||
## GenericViewSet
|
||||
|
||||
::: rest_framework.viewsets.GenericViewSet
|
||||
|
||||
The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default.
|
||||
|
||||
In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
|
||||
|
||||
## ModelViewSet
|
||||
|
||||
::: rest_framework.viewsets.ModelViewSet
|
||||
|
||||
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()`.
|
||||
|
@ -288,6 +295,8 @@ Also note that although this class provides the complete set of create/list/retr
|
|||
|
||||
## ReadOnlyModelViewSet
|
||||
|
||||
::: rest_framework.viewsets.ReadOnlyModelViewSet
|
||||
|
||||
The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`.
|
||||
|
||||
#### Example
|
||||
|
|
11
mkdocs.yml
11
mkdocs.yml
|
@ -16,6 +16,17 @@ markdown_extensions:
|
|||
plugins:
|
||||
- mkdocstrings:
|
||||
enable_inventory: true
|
||||
default_handler: python
|
||||
handlers:
|
||||
python:
|
||||
options:
|
||||
show_bases: false
|
||||
show_source: false
|
||||
members: false
|
||||
show_docstring: false
|
||||
show_docstring_description: false
|
||||
inherited_members: false
|
||||
summary: false
|
||||
|
||||
nav:
|
||||
- Home: 'index.md'
|
||||
|
|
Loading…
Reference in New Issue
Block a user