mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-24 02:24:03 +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
|
## 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.
|
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.
|
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
|
## TokenAuthentication
|
||||||
|
|
||||||
|
::: rest_framework.authentication.TokenAuthentication
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
|
**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
|
## 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.
|
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.
|
If successfully authenticated, `SessionAuthentication` provides the following credentials.
|
||||||
|
@ -300,6 +306,8 @@ CSRF validation in REST framework works slightly differently from standard Djang
|
||||||
|
|
||||||
## RemoteUserAuthentication
|
## RemoteUserAuthentication
|
||||||
|
|
||||||
|
::: rest_framework.authentication.RemoteUserAuthentication
|
||||||
|
|
||||||
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
|
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
|
||||||
environment variable.
|
environment variable.
|
||||||
|
|
||||||
|
|
|
@ -97,6 +97,8 @@ Note that the exception handler will only be called for responses generated by r
|
||||||
|
|
||||||
## APIException
|
## APIException
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.APIException
|
||||||
|
|
||||||
**Signature:** `APIException()`
|
**Signature:** `APIException()`
|
||||||
|
|
||||||
The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
|
The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
|
||||||
|
@ -145,6 +147,8 @@ dictionary of items:
|
||||||
|
|
||||||
## ParseError
|
## ParseError
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.ParseError
|
||||||
|
|
||||||
**Signature:** `ParseError(detail=None, code=None)`
|
**Signature:** `ParseError(detail=None, code=None)`
|
||||||
|
|
||||||
Raised if the request contains malformed data when accessing `request.data`.
|
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
|
## AuthenticationFailed
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.AuthenticationFailed
|
||||||
|
|
||||||
**Signature:** `AuthenticationFailed(detail=None, code=None)`
|
**Signature:** `AuthenticationFailed(detail=None, code=None)`
|
||||||
|
|
||||||
Raised when an incoming request includes incorrect authentication.
|
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
|
## NotAuthenticated
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.NotAuthenticated
|
||||||
|
|
||||||
**Signature:** `NotAuthenticated(detail=None, code=None)`
|
**Signature:** `NotAuthenticated(detail=None, code=None)`
|
||||||
|
|
||||||
Raised when an unauthenticated request fails the permission checks.
|
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
|
## PermissionDenied
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.PermissionDenied
|
||||||
|
|
||||||
**Signature:** `PermissionDenied(detail=None, code=None)`
|
**Signature:** `PermissionDenied(detail=None, code=None)`
|
||||||
|
|
||||||
Raised when an authenticated request fails the permission checks.
|
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
|
## NotFound
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.NotFound
|
||||||
|
|
||||||
**Signature:** `NotFound(detail=None, code=None)`
|
**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.
|
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
|
## MethodNotAllowed
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.MethodNotAllowed
|
||||||
|
|
||||||
**Signature:** `MethodNotAllowed(method, detail=None, code=None)`
|
**Signature:** `MethodNotAllowed(method, detail=None, code=None)`
|
||||||
|
|
||||||
Raised when an incoming request occurs that does not map to a handler method on the view.
|
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
|
## NotAcceptable
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.NotAcceptable
|
||||||
|
|
||||||
**Signature:** `NotAcceptable(detail=None, code=None)`
|
**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.
|
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
|
## UnsupportedMediaType
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.UnsupportedMediaType
|
||||||
|
|
||||||
**Signature:** `UnsupportedMediaType(media_type, detail=None, code=None)`
|
**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`.
|
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
|
## Throttled
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.Throttled
|
||||||
|
|
||||||
**Signature:** `Throttled(wait=None, detail=None, code=None)`
|
**Signature:** `Throttled(wait=None, detail=None, code=None)`
|
||||||
|
|
||||||
Raised when an incoming request fails the throttling checks.
|
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
|
## ValidationError
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.ValidationError
|
||||||
|
|
||||||
**Signature:** `ValidationError(detail=None, code=None)`
|
**Signature:** `ValidationError(detail=None, code=None)`
|
||||||
|
|
||||||
The `ValidationError` exception is slightly different from the other `APIException` classes:
|
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].
|
Use these as per [Django's Customizing error views documentation][django-custom-error-views].
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.server_error
|
||||||
|
|
||||||
## `rest_framework.exceptions.server_error`
|
## `rest_framework.exceptions.server_error`
|
||||||
|
|
||||||
Returns a response with status code `500` and `application/json` content type.
|
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'
|
handler500 = 'rest_framework.exceptions.server_error'
|
||||||
|
|
||||||
|
::: rest_framework.exceptions.bad_request
|
||||||
|
|
||||||
## `rest_framework.exceptions.bad_request`
|
## `rest_framework.exceptions.bad_request`
|
||||||
|
|
||||||
Returns a response with status code `400` and `application/json` content type.
|
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
|
## BooleanField
|
||||||
|
|
||||||
|
::: rest_framework.fields.BooleanField
|
||||||
|
|
||||||
A boolean representation.
|
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.
|
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
|
## CharField
|
||||||
|
|
||||||
|
::: rest_framework.fields.CharField
|
||||||
|
|
||||||
A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`.
|
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`.
|
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
|
## EmailField
|
||||||
|
|
||||||
|
::: rest_framework.fields.EmailField
|
||||||
|
|
||||||
A text representation, validates the text to be a valid e-mail address.
|
A text representation, validates the text to be a valid e-mail address.
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.EmailField`
|
Corresponds to `django.db.models.fields.EmailField`
|
||||||
|
@ -188,6 +194,8 @@ Corresponds to `django.db.models.fields.EmailField`
|
||||||
|
|
||||||
## RegexField
|
## RegexField
|
||||||
|
|
||||||
|
::: rest_framework.fields.RegexField
|
||||||
|
|
||||||
A text representation, that validates the given value matches against a certain regular expression.
|
A text representation, that validates the given value matches against a certain regular expression.
|
||||||
|
|
||||||
Corresponds to `django.forms.fields.RegexField`.
|
Corresponds to `django.forms.fields.RegexField`.
|
||||||
|
@ -200,6 +208,8 @@ Uses Django's `django.core.validators.RegexValidator` for validation.
|
||||||
|
|
||||||
## SlugField
|
## SlugField
|
||||||
|
|
||||||
|
::: rest_framework.fields.SlugField
|
||||||
|
|
||||||
A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`.
|
A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`.
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.SlugField`.
|
Corresponds to `django.db.models.fields.SlugField`.
|
||||||
|
@ -208,6 +218,8 @@ Corresponds to `django.db.models.fields.SlugField`.
|
||||||
|
|
||||||
## URLField
|
## 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>`.
|
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.
|
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
|
## 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:
|
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"
|
"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
|
## FilePathField
|
||||||
|
|
||||||
|
::: rest_framework.fields.FilePathField
|
||||||
|
|
||||||
A field whose choices are limited to the filenames in a certain directory on the filesystem
|
A field whose choices are limited to the filenames in a certain directory on the filesystem
|
||||||
|
|
||||||
Corresponds to `django.forms.fields.FilePathField`.
|
Corresponds to `django.forms.fields.FilePathField`.
|
||||||
|
@ -245,6 +261,8 @@ Corresponds to `django.forms.fields.FilePathField`.
|
||||||
|
|
||||||
## IPAddressField
|
## IPAddressField
|
||||||
|
|
||||||
|
::: rest_framework.fields.IPAddressField
|
||||||
|
|
||||||
A field that ensures the input is a valid IPv4 or IPv6 string.
|
A field that ensures the input is a valid IPv4 or IPv6 string.
|
||||||
|
|
||||||
Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.GenericIPAddressField`.
|
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
|
## IntegerField
|
||||||
|
|
||||||
|
::: rest_framework.fields.IntegerField
|
||||||
|
|
||||||
An integer representation.
|
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`.
|
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
|
## FloatField
|
||||||
|
|
||||||
|
::: rest_framework.fields.FloatField
|
||||||
|
|
||||||
A floating point representation.
|
A floating point representation.
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.FloatField`.
|
Corresponds to `django.db.models.fields.FloatField`.
|
||||||
|
@ -282,6 +304,8 @@ Corresponds to `django.db.models.fields.FloatField`.
|
||||||
|
|
||||||
## DecimalField
|
## DecimalField
|
||||||
|
|
||||||
|
::: rest_framework.fields.DecimalField
|
||||||
|
|
||||||
A decimal representation, represented in Python by a `Decimal` instance.
|
A decimal representation, represented in Python by a `Decimal` instance.
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.DecimalField`.
|
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
|
## DateTimeField
|
||||||
|
|
||||||
|
::: rest_framework.fields.DateTimeField
|
||||||
|
|
||||||
A date and time representation.
|
A date and time representation.
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.DateTimeField`.
|
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
|
## DateField
|
||||||
|
|
||||||
|
::: rest_framework.fields.DateField
|
||||||
|
|
||||||
A date representation.
|
A date representation.
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.DateField`
|
Corresponds to `django.db.models.fields.DateField`
|
||||||
|
@ -358,6 +386,8 @@ Format strings may either be [Python strftime formats][strftime] which explicitl
|
||||||
|
|
||||||
## TimeField
|
## TimeField
|
||||||
|
|
||||||
|
::: rest_framework.fields.TimeField
|
||||||
|
|
||||||
A time representation.
|
A time representation.
|
||||||
|
|
||||||
Corresponds to `django.db.models.fields.TimeField`
|
Corresponds to `django.db.models.fields.TimeField`
|
||||||
|
@ -373,6 +403,8 @@ Format strings may either be [Python strftime formats][strftime] which explicitl
|
||||||
|
|
||||||
## DurationField
|
## DurationField
|
||||||
|
|
||||||
|
::: rest_framework.fields.DurationField
|
||||||
|
|
||||||
A Duration representation.
|
A Duration representation.
|
||||||
Corresponds to `django.db.models.fields.DurationField`
|
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
|
## ChoiceField
|
||||||
|
|
||||||
|
::: rest_framework.fields.ChoiceField
|
||||||
|
|
||||||
A field that can accept a value out of a limited set of choices.
|
A field that can accept a value out of a limited set of choices.
|
||||||
|
|
||||||
Used by `ModelSerializer` to automatically generate fields if the corresponding model field includes a `choices=…` argument.
|
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
|
## 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.
|
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)`
|
**Signature:** `MultipleChoiceField(choices)`
|
||||||
|
@ -427,6 +463,8 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
|
||||||
|
|
||||||
## FileField
|
## FileField
|
||||||
|
|
||||||
|
::: rest_framework.fields.FileField
|
||||||
|
|
||||||
A file representation. Performs Django's standard FileField validation.
|
A file representation. Performs Django's standard FileField validation.
|
||||||
|
|
||||||
Corresponds to `django.forms.fields.FileField`.
|
Corresponds to `django.forms.fields.FileField`.
|
||||||
|
@ -439,6 +477,8 @@ Corresponds to `django.forms.fields.FileField`.
|
||||||
|
|
||||||
## ImageField
|
## ImageField
|
||||||
|
|
||||||
|
::: rest_framework.fields.ImageField
|
||||||
|
|
||||||
An image representation. Validates the uploaded file content as matching a known image format.
|
An image representation. Validates the uploaded file content as matching a known image format.
|
||||||
|
|
||||||
Corresponds to `django.forms.fields.ImageField`.
|
Corresponds to `django.forms.fields.ImageField`.
|
||||||
|
@ -457,6 +497,8 @@ Requires either the `Pillow` package or `PIL` package. The `Pillow` package is
|
||||||
|
|
||||||
## ListField
|
## ListField
|
||||||
|
|
||||||
|
::: rest_framework.fields.ListField
|
||||||
|
|
||||||
A field class that validates a list of objects.
|
A field class that validates a list of objects.
|
||||||
|
|
||||||
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
|
**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
|
## 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.
|
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)`
|
**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
|
## HStoreField
|
||||||
|
|
||||||
|
::: rest_framework.fields.HStoreField
|
||||||
|
|
||||||
A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`.
|
A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`.
|
||||||
|
|
||||||
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
**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
|
## 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.
|
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)`
|
**Signature**: `JSONField(binary, encoder)`
|
||||||
|
@ -523,6 +571,8 @@ A field class that validates that the incoming data structure consists of valid
|
||||||
|
|
||||||
## ReadOnlyField
|
## ReadOnlyField
|
||||||
|
|
||||||
|
::: rest_framework.fields.ReadOnlyField
|
||||||
|
|
||||||
A field class that simply returns the value of the field without modification.
|
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.
|
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
|
## 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.
|
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()`
|
**Signature**: `HiddenField()`
|
||||||
|
@ -558,6 +610,8 @@ For further examples on `HiddenField` see the [validators](validators.md) docume
|
||||||
|
|
||||||
## ModelField
|
## 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.
|
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.
|
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
|
## 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.
|
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)`
|
**Signature**: `SerializerMethodField(method_name=None)`
|
||||||
|
|
|
@ -190,6 +190,8 @@ It's also recommended that you read the section on [DRF integration][django-filt
|
||||||
|
|
||||||
## SearchFilter
|
## 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].
|
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:
|
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
|
## OrderingFilter
|
||||||
|
|
||||||
|
::: rest_framework.filters.OrderingFilter
|
||||||
|
|
||||||
The `OrderingFilter` class supports simple query parameter controlled ordering of results.
|
The `OrderingFilter` class supports simple query parameter controlled ordering of results.
|
||||||
|
|
||||||
![Ordering Filter](../img/ordering-filter.png)
|
![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
|
# 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.
|
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.
|
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
|
## GenericAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.GenericAPIView
|
||||||
|
|
||||||
This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views.
|
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.
|
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)`
|
#### `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.
|
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.
|
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)`
|
#### `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.
|
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.
|
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)`
|
#### `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.
|
Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
|
@ -143,6 +151,8 @@ For example:
|
||||||
|
|
||||||
#### `get_serializer_class(self)`
|
#### `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.
|
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.
|
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
|
## ListModelMixin
|
||||||
|
|
||||||
|
::: rest_framework.mixins.ListModelMixin
|
||||||
|
|
||||||
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
||||||
|
|
||||||
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
|
If the queryset is 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
|
## CreateModelMixin
|
||||||
|
|
||||||
|
::: rest_framework.mixins.CreateModelMixin
|
||||||
|
|
||||||
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
||||||
|
|
||||||
If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
|
If 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
|
## RetrieveModelMixin
|
||||||
|
|
||||||
|
::: rest_framework.mixins.RetrieveModelMixin
|
||||||
|
|
||||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
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`.
|
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
|
## UpdateModelMixin
|
||||||
|
|
||||||
|
::: rest_framework.mixins.UpdateModelMixin
|
||||||
|
|
||||||
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
|
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.
|
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
|
## DestroyModelMixin
|
||||||
|
|
||||||
|
::: rest_framework.mixins.DestroyModelMixin
|
||||||
|
|
||||||
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
|
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`.
|
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
|
## CreateAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.CreateAPIView
|
||||||
|
|
||||||
Used for **create-only** endpoints.
|
Used for **create-only** endpoints.
|
||||||
|
|
||||||
Provides a `post` method handler.
|
Provides a `post` method handler.
|
||||||
|
@ -253,6 +275,8 @@ Extends: [GenericAPIView], [CreateModelMixin]
|
||||||
|
|
||||||
## ListAPIView
|
## ListAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.ListAPIView
|
||||||
|
|
||||||
Used for **read-only** endpoints to represent a **collection of model instances**.
|
Used for **read-only** endpoints to represent a **collection of model instances**.
|
||||||
|
|
||||||
Provides a `get` method handler.
|
Provides a `get` method handler.
|
||||||
|
@ -261,6 +285,8 @@ Extends: [GenericAPIView], [ListModelMixin]
|
||||||
|
|
||||||
## RetrieveAPIView
|
## RetrieveAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.RetrieveAPIView
|
||||||
|
|
||||||
Used for **read-only** endpoints to represent a **single model instance**.
|
Used for **read-only** endpoints to represent a **single model instance**.
|
||||||
|
|
||||||
Provides a `get` method handler.
|
Provides a `get` method handler.
|
||||||
|
@ -269,6 +295,8 @@ Extends: [GenericAPIView], [RetrieveModelMixin]
|
||||||
|
|
||||||
## DestroyAPIView
|
## DestroyAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.DestroyAPIView
|
||||||
|
|
||||||
Used for **delete-only** endpoints for a **single model instance**.
|
Used for **delete-only** endpoints for a **single model instance**.
|
||||||
|
|
||||||
Provides a `delete` method handler.
|
Provides a `delete` method handler.
|
||||||
|
@ -277,6 +305,8 @@ Extends: [GenericAPIView], [DestroyModelMixin]
|
||||||
|
|
||||||
## UpdateAPIView
|
## UpdateAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.UpdateAPIView
|
||||||
|
|
||||||
Used for **update-only** endpoints for a **single model instance**.
|
Used for **update-only** endpoints for a **single model instance**.
|
||||||
|
|
||||||
Provides `put` and `patch` method handlers.
|
Provides `put` and `patch` method handlers.
|
||||||
|
@ -285,6 +315,8 @@ Extends: [GenericAPIView], [UpdateModelMixin]
|
||||||
|
|
||||||
## ListCreateAPIView
|
## ListCreateAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.ListCreateAPIView
|
||||||
|
|
||||||
Used for **read-write** endpoints to represent a **collection of model instances**.
|
Used for **read-write** endpoints to represent a **collection of model instances**.
|
||||||
|
|
||||||
Provides `get` and `post` method handlers.
|
Provides `get` and `post` method handlers.
|
||||||
|
@ -293,6 +325,8 @@ Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin]
|
||||||
|
|
||||||
## RetrieveUpdateAPIView
|
## RetrieveUpdateAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.RetrieveUpdateAPIView
|
||||||
|
|
||||||
Used for **read or update** endpoints to represent a **single model instance**.
|
Used for **read or update** endpoints to represent a **single model instance**.
|
||||||
|
|
||||||
Provides `get`, `put` and `patch` method handlers.
|
Provides `get`, `put` and `patch` method handlers.
|
||||||
|
@ -301,6 +335,8 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin]
|
||||||
|
|
||||||
## RetrieveDestroyAPIView
|
## RetrieveDestroyAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.RetrieveDestroyAPIView
|
||||||
|
|
||||||
Used for **read or delete** endpoints to represent a **single model instance**.
|
Used for **read or delete** endpoints to represent a **single model instance**.
|
||||||
|
|
||||||
Provides `get` and `delete` method handlers.
|
Provides `get` and `delete` method handlers.
|
||||||
|
@ -309,6 +345,8 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin]
|
||||||
|
|
||||||
## RetrieveUpdateDestroyAPIView
|
## RetrieveUpdateDestroyAPIView
|
||||||
|
|
||||||
|
::: rest_framework.generics.RetrieveUpdateDestroyAPIView
|
||||||
|
|
||||||
Used for **read-write-delete** endpoints to represent a **single model instance**.
|
Used for **read-write-delete** endpoints to represent a **single model instance**.
|
||||||
|
|
||||||
Provides `get`, `put`, `patch` and `delete` method handlers.
|
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
|
## PageNumberPagination
|
||||||
|
|
||||||
|
::: rest_framework.pagination.PageNumberPagination
|
||||||
|
|
||||||
This pagination style accepts a single number page number in the request query parameters.
|
This pagination style accepts a single number page number in the request query parameters.
|
||||||
|
|
||||||
**Request**:
|
**Request**:
|
||||||
|
@ -115,6 +117,8 @@ To set these attributes you should override the `PageNumberPagination` class, an
|
||||||
|
|
||||||
## LimitOffsetPagination
|
## 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
|
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.
|
"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
|
## 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.
|
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.
|
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
|
# 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:
|
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.
|
* 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
|
## JSONParser
|
||||||
|
|
||||||
|
::: rest_framework.parsers.JSONParser
|
||||||
|
|
||||||
Parses `JSON` request content. `request.data` will be populated with a dictionary of data.
|
Parses `JSON` request content. `request.data` will be populated with a dictionary of data.
|
||||||
|
|
||||||
**.media_type**: `application/json`
|
**.media_type**: `application/json`
|
||||||
|
|
||||||
## FormParser
|
## FormParser
|
||||||
|
|
||||||
|
::: rest_framework.parsers.FormParser
|
||||||
|
|
||||||
Parses HTML form content. `request.data` will be populated with a `QueryDict` of data.
|
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.
|
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
|
## 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.
|
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.
|
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
|
## 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.
|
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.
|
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
|
# 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.
|
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.
|
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
|
## AllowAny
|
||||||
|
|
||||||
|
::: rest_framework.permissions.AllowAny
|
||||||
|
|
||||||
The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**.
|
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.
|
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
|
## IsAuthenticated
|
||||||
|
|
||||||
|
::: rest_framework.permissions.IsAuthenticated
|
||||||
|
|
||||||
The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise.
|
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.
|
This permission is suitable if you want your API to only be accessible to registered users.
|
||||||
|
|
||||||
## IsAdminUser
|
## 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.
|
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.
|
This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.
|
||||||
|
|
||||||
## IsAuthenticatedOrReadOnly
|
## 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`.
|
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.
|
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
|
## 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`.
|
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.
|
* `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
|
## DjangoModelPermissionsOrAnonReadOnly
|
||||||
|
|
||||||
|
::: rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly
|
||||||
|
|
||||||
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
|
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
|
||||||
|
|
||||||
## DjangoObjectPermissions
|
## DjangoObjectPermissions
|
||||||
|
@ -207,6 +219,8 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid
|
||||||
|
|
||||||
# Custom permissions
|
# Custom permissions
|
||||||
|
|
||||||
|
::: rest_framework.permissions.BasePermission
|
||||||
|
|
||||||
To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods:
|
To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods:
|
||||||
|
|
||||||
* `.has_permission(self, request, view)`
|
* `.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
|
## StringRelatedField
|
||||||
|
|
||||||
|
::: rest_framework.relations.StringRelatedField
|
||||||
|
|
||||||
`StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
|
`StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
|
||||||
|
|
||||||
For example, the following serializer:
|
For example, the following serializer:
|
||||||
|
@ -117,6 +119,8 @@ This field is read only.
|
||||||
|
|
||||||
## PrimaryKeyRelatedField
|
## PrimaryKeyRelatedField
|
||||||
|
|
||||||
|
::: rest_framework.relations.PrimaryKeyRelatedField
|
||||||
|
|
||||||
`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
|
`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
|
||||||
|
|
||||||
For example, the following serializer:
|
For example, the following serializer:
|
||||||
|
@ -153,6 +157,8 @@ By default this field is read-write, although you can change this behavior using
|
||||||
|
|
||||||
## HyperlinkedRelatedField
|
## HyperlinkedRelatedField
|
||||||
|
|
||||||
|
::: rest_framework.relations.HyperlinkedRelatedField
|
||||||
|
|
||||||
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
|
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
|
||||||
|
|
||||||
For example, the following serializer:
|
For example, the following serializer:
|
||||||
|
@ -205,6 +211,8 @@ If you require more complex hyperlinked representation you'll need to customize
|
||||||
|
|
||||||
## SlugRelatedField
|
## SlugRelatedField
|
||||||
|
|
||||||
|
::: rest_framework.relations.SlugRelatedField
|
||||||
|
|
||||||
`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
|
`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
|
||||||
|
|
||||||
For example, the following serializer:
|
For example, the following serializer:
|
||||||
|
@ -246,6 +254,8 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
|
||||||
|
|
||||||
## HyperlinkedIdentityField
|
## 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:
|
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):
|
||||||
|
@ -362,6 +372,8 @@ By default nested serializers are read-only. If you want to support write-operat
|
||||||
|
|
||||||
# Custom relational fields
|
# Custom relational fields
|
||||||
|
|
||||||
|
::: rest_framework.relations.RelatedField
|
||||||
|
|
||||||
In rare cases where none of the existing relational styles fit the representation you need,
|
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
|
you can implement a completely custom relational field, that describes exactly how the
|
||||||
output representation should be generated from the model instance.
|
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
|
## JSONRenderer
|
||||||
|
|
||||||
|
::: rest_framework.renderers.JSONRenderer
|
||||||
|
|
||||||
Renders the request data into `JSON`, using utf-8 encoding.
|
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:
|
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
|
## TemplateHTMLRenderer
|
||||||
|
|
||||||
|
::: rest_framework.renderers.TemplateHTMLRenderer
|
||||||
|
|
||||||
Renders data to HTML, using Django's standard template rendering.
|
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`.
|
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
|
## 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.
|
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`:
|
An example of a view that uses `StaticHTMLRenderer`:
|
||||||
|
@ -170,6 +176,8 @@ See also: `TemplateHTMLRenderer`
|
||||||
|
|
||||||
## BrowsableAPIRenderer
|
## BrowsableAPIRenderer
|
||||||
|
|
||||||
|
::: rest_framework.renderers.BrowsableAPIRenderer
|
||||||
|
|
||||||
Renders data into HTML for the Browsable API:
|
Renders data into HTML for the Browsable API:
|
||||||
|
|
||||||
![The BrowsableAPIRenderer](../img/quickstart.png)
|
![The BrowsableAPIRenderer](../img/quickstart.png)
|
||||||
|
@ -194,6 +202,8 @@ By default the response content will be rendered with the highest priority rende
|
||||||
|
|
||||||
## AdminRenderer
|
## AdminRenderer
|
||||||
|
|
||||||
|
::: rest_framework.renderers.AdminRenderer
|
||||||
|
|
||||||
Renders data into HTML for an admin-like display:
|
Renders data into HTML for an admin-like display:
|
||||||
|
|
||||||
![The AdminRender view](../img/admin.png)
|
![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
|
## 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.
|
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.
|
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
|
## 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].
|
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`
|
**.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
|
# 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.
|
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.
|
The method should return a bytestring, which will be used as the body of the HTTP response.
|
||||||
|
|
|
@ -5,6 +5,8 @@ source:
|
||||||
|
|
||||||
# Requests
|
# Requests
|
||||||
|
|
||||||
|
::: rest_framework.request.Request
|
||||||
|
|
||||||
> If you're doing REST-based web service stuff ... you should ignore request.POST.
|
> If you're doing REST-based web service stuff ... you should ignore request.POST.
|
||||||
>
|
>
|
||||||
> — Malcom Tredinnick, [Django developers group][cite]
|
> — Malcom Tredinnick, [Django developers group][cite]
|
||||||
|
@ -15,6 +17,7 @@ REST framework's `Request` class extends the standard `HttpRequest`, adding supp
|
||||||
|
|
||||||
# Request parsing
|
# 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.
|
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
|
## .data
|
||||||
|
|
|
@ -21,8 +21,11 @@ Unless you want to heavily customize REST framework for some reason, you should
|
||||||
|
|
||||||
# Creating responses
|
# Creating responses
|
||||||
|
|
||||||
|
|
||||||
## Response()
|
## Response()
|
||||||
|
|
||||||
|
::: rest_framework.response.Response
|
||||||
|
|
||||||
**Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)`
|
**Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)`
|
||||||
|
|
||||||
Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.
|
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
|
## reverse
|
||||||
|
|
||||||
|
::: rest_framework.reverse.reverse
|
||||||
|
|
||||||
**Signature:** `reverse(viewname, *args, **kwargs)`
|
**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.
|
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
|
## reverse_lazy
|
||||||
|
|
||||||
|
::: rest_framework.reverse.reverse_lazy
|
||||||
|
|
||||||
**Signature:** `reverse_lazy(viewname, *args, **kwargs)`
|
**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.
|
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
|
## 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.
|
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>
|
<table border=1>
|
||||||
|
@ -187,6 +189,8 @@ Trailing slashes are conventional in Django, but are not used by default in some
|
||||||
|
|
||||||
## DefaultRouter
|
## 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.
|
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>
|
<table border=1>
|
||||||
|
@ -315,6 +319,8 @@ For another example of setting the `.routes` attribute, see the source code for
|
||||||
|
|
||||||
## Advanced custom routers
|
## 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.
|
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.
|
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
|
## Declaring Serializers
|
||||||
|
|
||||||
|
::: rest_framework.serializers.Serializer
|
||||||
|
|
||||||
Let's start by creating a simple object we can use for example purposes:
|
Let's start by creating a simple object we can use for example purposes:
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
@ -149,6 +151,8 @@ Note that in the case above we're now having to access the serializer `.validate
|
||||||
|
|
||||||
## Validation
|
## 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:
|
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'})
|
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
|
# ModelSerializer
|
||||||
|
|
||||||
|
::: rest_framework.serializers.ModelSerializer
|
||||||
|
|
||||||
Often you'll want serializer classes that map closely to Django model definitions.
|
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.
|
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
|
# 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.
|
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.
|
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
|
# 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.
|
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`
|
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
|
# BaseSerializer
|
||||||
|
|
||||||
|
::: rest_framework.serializers.BaseSerializer
|
||||||
|
|
||||||
`BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles.
|
`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:
|
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
|
## 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 `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).
|
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
|
## 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 `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).
|
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
|
## 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 `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".
|
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
|
# 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.
|
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`.
|
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
|
## UniqueValidator
|
||||||
|
|
||||||
|
::: rest_framework.validators.UniqueValidator
|
||||||
|
|
||||||
This validator can be used to enforce the `unique=True` constraint on model fields.
|
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:
|
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())]
|
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.
|
This validator can be used to enforce `unique_together` constraints on model instances.
|
||||||
It has two required arguments, and a single optional `messages` argument:
|
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
|
## UniqueForDateValidator
|
||||||
|
|
||||||
|
::: rest_framework.validators.UniqueForDateValidator
|
||||||
|
|
||||||
## UniqueForMonthValidator
|
## UniqueForMonthValidator
|
||||||
|
|
||||||
|
::: rest_framework.validators.UniqueForMonthValidator
|
||||||
|
|
||||||
## UniqueForYearValidator
|
## 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:
|
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.
|
* `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
|
#### 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.
|
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(
|
owner = serializers.HiddenField(
|
||||||
|
@ -189,6 +202,9 @@ A default class that can be used to represent the current user. In order to use
|
||||||
|
|
||||||
#### CreateOnlyDefault
|
#### 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.
|
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.
|
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
|
# 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.
|
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
|
## URLPathVersioning
|
||||||
|
|
||||||
|
::: rest_framework.versioning.URLPathVersioning
|
||||||
|
|
||||||
This scheme requires the client to specify the version as part of the URL path.
|
This scheme requires the client to specify the version as part of the URL path.
|
||||||
|
|
||||||
GET /v1/bookings/ HTTP/1.1
|
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
|
## 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.
|
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
|
GET /v1/something/ HTTP/1.1
|
||||||
|
@ -172,6 +178,8 @@ Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just ne
|
||||||
|
|
||||||
## HostNameVersioning
|
## 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.
|
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:
|
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
|
## QueryParameterVersioning
|
||||||
|
|
||||||
|
::: rest_framework.versioning.QueryParameterVersioning
|
||||||
|
|
||||||
This scheme is a simple style that includes the version as a query parameter in the URL. For example:
|
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
|
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
|
# Custom versioning schemes
|
||||||
|
|
||||||
|
::: rest_framework.versioning.BaseVersioning
|
||||||
|
|
||||||
To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method.
|
To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method.
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
|
@ -12,6 +12,8 @@ source:
|
||||||
|
|
||||||
REST framework provides an `APIView` class, which subclasses Django's `View` class.
|
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:
|
`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.
|
* 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
|
### .renderer_classes
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.renderer_classes
|
||||||
|
|
||||||
### .parser_classes
|
### .parser_classes
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.parser_classes
|
||||||
|
|
||||||
### .authentication_classes
|
### .authentication_classes
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.authentication_classes
|
||||||
|
|
||||||
### .throttle_classes
|
### .throttle_classes
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.throttle_classes
|
||||||
|
|
||||||
### .permission_classes
|
### .permission_classes
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.permission_classes
|
||||||
|
|
||||||
### .content_negotiation_class
|
### .content_negotiation_class
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.content_negotiation_class
|
||||||
|
|
||||||
## API policy instantiation methods
|
## 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.
|
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)
|
### .get_renderers(self)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.get_renderers
|
||||||
|
|
||||||
### .get_parsers(self)
|
### .get_parsers(self)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.get_parsers
|
||||||
|
|
||||||
### .get_authenticators(self)
|
### .get_authenticators(self)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.get_authenticators
|
||||||
|
|
||||||
### .get_throttles(self)
|
### .get_throttles(self)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.get_throttles
|
||||||
|
|
||||||
### .get_permissions(self)
|
### .get_permissions(self)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.get_permissions
|
||||||
|
|
||||||
### .get_content_negotiator(self)
|
### .get_content_negotiator(self)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.get_content_negotiator
|
||||||
|
|
||||||
### .get_exception_handler(self)
|
### .get_exception_handler(self)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.get_exception_handler
|
||||||
|
|
||||||
## API policy implementation methods
|
## API policy implementation methods
|
||||||
|
|
||||||
The following methods are called before dispatching to the handler method.
|
The following methods are called before dispatching to the handler method.
|
||||||
|
|
||||||
### .check_permissions(self, request)
|
### .check_permissions(self, request)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.check_permissions
|
||||||
|
|
||||||
### .check_throttles(self, request)
|
### .check_throttles(self, request)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.check_throttles
|
||||||
|
|
||||||
### .perform_content_negotiation(self, request, force=False)
|
### .perform_content_negotiation(self, request, force=False)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.perform_content_negotiation
|
||||||
|
|
||||||
## Dispatch methods
|
## Dispatch methods
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.dispatch
|
||||||
|
|
||||||
The following methods are called directly by the view's `.dispatch()` method.
|
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()`.
|
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)
|
### .initial(self, request, \*args, **kwargs)
|
||||||
|
|
||||||
|
::: rest_framework.views.APIView.initial
|
||||||
|
|
||||||
Performs any actions that need to occur before the handler method gets called.
|
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.
|
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)
|
### .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.
|
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.
|
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)
|
### .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`.
|
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.
|
You won't typically need to override this method.
|
||||||
|
|
||||||
### .finalize_response(self, request, response, \*args, **kwargs)
|
### .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.
|
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.
|
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()
|
## @api_view()
|
||||||
|
|
||||||
|
::: rest_framework.decorators.api_view
|
||||||
|
|
||||||
**Signature:** `@api_view(http_method_names=['GET'])`
|
**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:
|
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
|
## View schema decorator
|
||||||
|
|
||||||
|
::: rest_framework.decorators.schema
|
||||||
|
|
||||||
To override the default schema generation for function based views you may use
|
To override the default schema generation for function based views you may use
|
||||||
the `@schema` decorator. This must come *after* (below) the `@api_view`
|
the `@schema` decorator. This must come *after* (below) the `@api_view`
|
||||||
decorator. For example:
|
decorator. For example:
|
||||||
|
|
|
@ -9,6 +9,7 @@ source:
|
||||||
>
|
>
|
||||||
> — [Ruby on Rails Documentation][cite]
|
> — [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'.
|
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
|
## 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.
|
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:
|
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
|
## 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.
|
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.
|
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
|
## 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 `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()`.
|
||||||
|
@ -288,6 +295,8 @@ Also note that although this class provides the complete set of create/list/retr
|
||||||
|
|
||||||
## ReadOnlyModelViewSet
|
## 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()`.
|
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
|
#### Example
|
||||||
|
|
11
mkdocs.yml
11
mkdocs.yml
|
@ -16,6 +16,17 @@ markdown_extensions:
|
||||||
plugins:
|
plugins:
|
||||||
- mkdocstrings:
|
- mkdocstrings:
|
||||||
enable_inventory: true
|
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:
|
nav:
|
||||||
- Home: 'index.md'
|
- Home: 'index.md'
|
||||||
|
|
Loading…
Reference in New Issue
Block a user