django-rest-framework/docs/api-guide/settings.md

479 lines
15 KiB
Markdown
Raw Normal View History

source: settings.py
2012-09-09 01:06:13 +04:00
2012-09-05 13:01:43 +04:00
# Settings
2012-09-12 13:12:13 +04:00
> Namespaces are one honking great idea - let's do more of those!
>
> — [The Zen of Python][cite]
2012-09-06 00:14:00 +04:00
Configuration for REST framework is all namespaced inside a single Django setting, named `REST_FRAMEWORK`.
2012-09-12 13:12:13 +04:00
For example your project's `settings.py` file might include something like this:
2012-09-05 13:01:43 +04:00
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
2014-11-29 21:43:05 +03:00
'rest_framework.renderers.JSONRenderer',
2012-10-31 13:41:56 +04:00
),
'DEFAULT_PARSER_CLASSES': (
2014-11-29 21:43:05 +03:00
'rest_framework.parsers.JSONParser',
2012-09-05 13:01:43 +04:00
)
}
2012-09-06 19:46:56 +04:00
## Accessing settings
If you need to access the values of REST framework's API settings in your project,
you should use the `api_settings` object. For example.
from rest_framework.settings import api_settings
print(api_settings.DEFAULT_AUTHENTICATION_CLASSES)
2012-09-06 19:46:56 +04:00
2013-08-07 22:00:06 +04:00
The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
2012-09-06 19:46:56 +04:00
2012-10-17 18:41:57 +04:00
---
# API Reference
2013-03-06 16:19:39 +04:00
## API policy settings
*The following settings control the basic API policies, and are applied to every `APIView` class-based view, or `@api_view` function based view.*
2013-03-06 16:19:39 +04:00
#### DEFAULT_RENDERER_CLASSES
2012-09-05 13:01:43 +04:00
2012-09-05 16:03:55 +04:00
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object.
2012-09-05 13:01:43 +04:00
Default:
(
'rest_framework.renderers.JSONRenderer',
2012-10-29 12:13:56 +04:00
'rest_framework.renderers.BrowsableAPIRenderer',
2012-09-05 16:03:55 +04:00
)
2012-09-05 13:01:43 +04:00
2013-03-06 16:19:39 +04:00
#### DEFAULT_PARSER_CLASSES
2012-09-05 13:01:43 +04:00
A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.data` property.
2012-09-05 16:03:55 +04:00
Default:
(
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
2012-09-05 16:03:55 +04:00
)
2013-03-06 16:19:39 +04:00
#### DEFAULT_AUTHENTICATION_CLASSES
2012-09-05 16:03:55 +04:00
A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties.
2012-09-06 18:57:16 +04:00
Default:
2012-09-05 16:03:55 +04:00
(
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
2012-09-05 16:03:55 +04:00
)
2013-03-06 16:19:39 +04:00
#### DEFAULT_PERMISSION_CLASSES
2012-09-05 16:03:55 +04:00
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.
2012-09-06 00:14:00 +04:00
2012-10-27 23:04:33 +04:00
Default:
(
'rest_framework.permissions.AllowAny',
)
2012-09-05 16:03:55 +04:00
2013-03-06 16:19:39 +04:00
#### DEFAULT_THROTTLE_CLASSES
2012-09-05 13:01:43 +04:00
2012-09-06 00:14:00 +04:00
A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
2012-09-05 13:01:43 +04:00
Default: `()`
2012-09-05 16:03:55 +04:00
2013-03-06 16:19:39 +04:00
#### DEFAULT_CONTENT_NEGOTIATION_CLASS
A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
#### DEFAULT_SCHEMA_CLASS
A view inspector class that will be used for schema generation.
Default: `'rest_framework.schemas.AutoSchema'`
2013-03-06 16:19:39 +04:00
---
## Generic view settings
*The following settings control the behavior of the generic class-based views.*
2013-03-06 16:19:39 +04:00
#### DEFAULT_PAGINATION_SERIALIZER_CLASS
2012-09-05 16:03:55 +04:00
---
**This setting has been removed.**
2012-09-06 19:46:56 +04:00
The pagination API does not use serializers to determine the output format, and
you'll need to instead override the `get_paginated_response method on a
pagination class in order to specify how the output format is controlled.
---
2012-09-05 16:03:55 +04:00
2013-05-07 16:00:44 +04:00
#### DEFAULT_FILTER_BACKENDS
2012-09-05 16:03:55 +04:00
2013-05-07 16:00:44 +04:00
A list of filter backend classes that should be used for generic filtering.
If set to `None` then generic filtering is disabled.
2012-09-06 19:46:56 +04:00
2013-03-06 16:19:39 +04:00
#### PAGINATE_BY
---
2016-03-08 08:39:58 +03:00
**This setting has been removed.**
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
---
2016-03-08 08:40:33 +03:00
#### PAGE_SIZE
2016-03-08 08:40:33 +03:00
The default page size to use for pagination. If set to `None`, pagination is disabled by default.
Default: `None`
#### PAGINATE_BY_PARAM
---
**This setting has been removed.**
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
---
#### MAX_PAGINATE_BY
---
2018-04-03 16:35:26 +03:00
**This setting has been removed.**
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
---
2012-09-05 16:03:55 +04:00
### SEARCH_PARAM
2014-11-07 10:19:26 +03:00
The name of a query parameter, which can be used to specify the search term used by `SearchFilter`.
Default: `search`
#### ORDERING_PARAM
2014-11-07 10:19:26 +03:00
The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`.
Default: `ordering`
2013-03-06 16:19:39 +04:00
---
## Versioning settings
#### DEFAULT_VERSION
The value that should be used for `request.version` when no versioning information is present.
Default: `None`
#### ALLOWED_VERSIONS
If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.
Default: `None`
#### VERSION_PARAM
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
Default: `'version'`
---
2013-03-06 16:19:39 +04:00
## Authentication settings
*The following settings control the behavior of unauthenticated requests.*
#### UNAUTHENTICATED_USER
2012-09-05 23:10:06 +04:00
The class that should be used to initialize `request.user` for unauthenticated requests.
(If removing authentication entirely, e.g. by removing `django.contrib.auth` from
`INSTALLED_APPS`, set `UNAUTHENTICATED_USER` to `None`.)
2012-09-05 16:03:55 +04:00
Default: `django.contrib.auth.models.AnonymousUser`
2013-03-06 16:19:39 +04:00
#### UNAUTHENTICATED_TOKEN
2012-09-05 23:10:06 +04:00
The class that should be used to initialize `request.auth` for unauthenticated requests.
Default: `None`
2013-03-06 16:19:39 +04:00
---
2013-07-01 16:59:05 +04:00
## Test settings
*The following settings control the behavior of APIRequestFactory and APIClient*
#### TEST_REQUEST_DEFAULT_FORMAT
The default format that should be used when making test requests.
This should match up with the format of one of the renderer classes in the `TEST_REQUEST_RENDERER_CLASSES` setting.
Default: `'multipart'`
#### TEST_REQUEST_RENDERER_CLASSES
The renderer classes that are supported when building test requests.
2013-08-07 22:00:06 +04:00
The format of any of these renderer classes may be used when constructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')`
2013-07-01 16:59:05 +04:00
Default:
(
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.JSONRenderer'
)
---
Version 3.5 (#4525) * Start test case * Added 'requests' test client * Address typos * Graceful fallback if requests is not installed. * Add cookie support * Tests for auth and CSRF * Py3 compat * py3 compat * py3 compat * Add get_requests_client * Added SchemaGenerator.should_include_link * add settings for html cutoff on related fields * Router doesn't work if prefix is blank, though project urls.py handles prefix * Fix Django 1.10 to-many deprecation * Add django.core.urlresolvers compatibility * Update django-filter & django-guardian * Check for empty router prefix; adjust URL accordingly It's easiest to fix this issue after we have made the regex. To try to fix it before would require doing something different for List vs Detail, which means we'd have to know which type of url we're constructing before acting accordingly. * Fix misc django deprecations * Use TOC extension instead of header * Fix deprecations for py3k * Add py3k compatibility to is_simple_callable * Add is_simple_callable tests * Drop python 3.2 support (EOL, Dropped by Django) * schema_renderers= should *set* the renderers, not append to them. * API client (#4424) * Fix release notes * Add note about 'User account is disabled.' vs 'Unable to log in' * Clean up schema generation (#4527) * Handle multiple methods on custom action (#4529) * RequestsClient, CoreAPIClient * exclude_from_schema * Added 'get_schema_view()' shortcut * Added schema descriptions * Better descriptions for schemas * Add type annotation to schema generation * Coerce schema 'pk' in path to actual field name * Deprecations move into assertion errors * Use get_schema_view in tests * Updte CoreJSON media type * Handle schema structure correctly when path prefixs exist. Closes #4401 * Add PendingDeprecation to Router schema generation. * Added SCHEMA_COERCE_PATH_PK and SCHEMA_COERCE_METHOD_NAMES * Renamed and documented 'get_schema_fields' interface.
2016-10-10 15:03:46 +03:00
## Schema generation controls
#### SCHEMA_COERCE_PATH_PK
If set, this maps the `'pk'` identifier in the URL conf onto the actual field
name when generating a schema path parameter. Typically this will be `'id'`.
This gives a more suitable representation as "primary key" is an implementation
2017-01-08 16:34:52 +03:00
detail, whereas "identifier" is a more general concept.
Version 3.5 (#4525) * Start test case * Added 'requests' test client * Address typos * Graceful fallback if requests is not installed. * Add cookie support * Tests for auth and CSRF * Py3 compat * py3 compat * py3 compat * Add get_requests_client * Added SchemaGenerator.should_include_link * add settings for html cutoff on related fields * Router doesn't work if prefix is blank, though project urls.py handles prefix * Fix Django 1.10 to-many deprecation * Add django.core.urlresolvers compatibility * Update django-filter & django-guardian * Check for empty router prefix; adjust URL accordingly It's easiest to fix this issue after we have made the regex. To try to fix it before would require doing something different for List vs Detail, which means we'd have to know which type of url we're constructing before acting accordingly. * Fix misc django deprecations * Use TOC extension instead of header * Fix deprecations for py3k * Add py3k compatibility to is_simple_callable * Add is_simple_callable tests * Drop python 3.2 support (EOL, Dropped by Django) * schema_renderers= should *set* the renderers, not append to them. * API client (#4424) * Fix release notes * Add note about 'User account is disabled.' vs 'Unable to log in' * Clean up schema generation (#4527) * Handle multiple methods on custom action (#4529) * RequestsClient, CoreAPIClient * exclude_from_schema * Added 'get_schema_view()' shortcut * Added schema descriptions * Better descriptions for schemas * Add type annotation to schema generation * Coerce schema 'pk' in path to actual field name * Deprecations move into assertion errors * Use get_schema_view in tests * Updte CoreJSON media type * Handle schema structure correctly when path prefixs exist. Closes #4401 * Add PendingDeprecation to Router schema generation. * Added SCHEMA_COERCE_PATH_PK and SCHEMA_COERCE_METHOD_NAMES * Renamed and documented 'get_schema_fields' interface.
2016-10-10 15:03:46 +03:00
Default: `True`
#### SCHEMA_COERCE_METHOD_NAMES
If set, this is used to map internal viewset method names onto external action
names used in the schema generation. This allows us to generate names that
are more suitable for an external representation than those that are used
internally in the codebase.
Default: `{'retrieve': 'read', 'destroy': 'delete'}`
---
2015-09-28 17:33:55 +03:00
## Content type controls
2013-03-06 16:19:39 +04:00
2015-09-28 17:33:55 +03:00
#### URL_FORMAT_OVERRIDE
2012-09-05 16:03:55 +04:00
2015-09-28 17:33:55 +03:00
The name of a URL parameter that may be used to override the default content negotiation `Accept` header behavior, by using a `format=…` query parameter in the request URL.
2012-09-05 16:03:55 +04:00
2015-09-28 17:33:55 +03:00
For example: `http://example.com/organizations/?format=csv`
2012-09-05 23:10:06 +04:00
2015-09-28 17:33:55 +03:00
If the value of this setting is `None` then URL format overrides will be disabled.
2012-09-06 00:14:00 +04:00
2015-09-28 17:33:55 +03:00
Default: `'format'`
2015-09-28 17:33:55 +03:00
#### FORMAT_SUFFIX_KWARG
2015-09-28 17:33:55 +03:00
The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using `format_suffix_patterns` to include suffixed URL patterns.
2015-09-28 17:33:55 +03:00
For example: `http://example.com/organizations.csv/`
Default: `'format'`
2012-09-12 13:12:13 +04:00
2013-03-06 16:19:39 +04:00
---
## Date and time formatting
2013-03-06 16:19:39 +04:00
*The following settings are used to control how date and time representations may be parsed and rendered.*
2013-03-06 16:19:39 +04:00
#### DATETIME_FORMAT
2013-03-01 18:03:27 +04:00
A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return Python `datetime` objects, and the datetime encoding will be determined by the renderer.
2013-03-01 18:03:27 +04:00
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
2014-09-12 15:40:53 +04:00
Default: `'iso-8601'`
2013-03-01 19:35:27 +04:00
2013-03-06 16:19:39 +04:00
#### DATETIME_INPUT_FORMATS
2013-03-01 18:03:27 +04:00
2013-03-06 00:57:35 +04:00
A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields.
2013-03-01 18:03:27 +04:00
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
2013-03-06 16:19:39 +04:00
Default: `['iso-8601']`
2013-03-01 18:03:27 +04:00
2013-03-06 16:19:39 +04:00
#### DATE_FORMAT
2013-03-01 19:35:27 +04:00
A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return Python `date` objects, and the date encoding will be determined by the renderer.
2013-03-06 00:57:35 +04:00
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
2014-09-12 15:40:53 +04:00
Default: `'iso-8601'`
2013-03-06 00:57:35 +04:00
2013-03-06 16:19:39 +04:00
#### DATE_INPUT_FORMATS
2013-03-01 18:03:27 +04:00
2013-03-06 00:57:35 +04:00
A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields.
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
2013-03-06 16:19:39 +04:00
Default: `['iso-8601']`
2013-03-06 00:57:35 +04:00
2013-03-06 16:19:39 +04:00
#### TIME_FORMAT
2013-03-06 00:57:35 +04:00
A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return Python `time` objects, and the time encoding will be determined by the renderer.
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
2013-03-06 00:57:35 +04:00
2014-09-12 15:40:53 +04:00
Default: `'iso-8601'`
2013-03-06 00:57:35 +04:00
2013-03-06 16:19:39 +04:00
#### TIME_INPUT_FORMATS
2013-03-01 18:03:27 +04:00
2013-03-06 00:57:35 +04:00
A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields.
2013-03-01 18:03:27 +04:00
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
2013-03-06 16:19:39 +04:00
Default: `['iso-8601']`
---
2014-09-12 15:40:53 +04:00
## Encodings
#### UNICODE_JSON
When set to `True`, JSON responses will allow unicode characters in responses. For example:
{"unicode black star":"★"}
When set to `False`, JSON responses will escape non-ascii characters, like so:
{"unicode black star":"\u2605"}
2014-11-07 10:19:26 +03:00
Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.
2014-09-12 15:40:53 +04:00
Default: `True`
#### COMPACT_JSON
When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example:
{"is_admin":false,"email":"jane@example"}
When set to `False`, JSON responses will return slightly more verbose representations, like so:
{"is_admin": false, "email": "jane@example"}
The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json].
Default: `True`
2017-07-11 02:34:04 +03:00
#### STRICT_JSON
When set to `True`, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (`nan`, `inf`, `-inf`) accepted by Python's `json` module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's `JSON.Parse` nor PostgreSQL's JSON data type accept these values.
When set to `False`, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code.
Default: `True`
2014-09-12 15:40:53 +04:00
#### COERCE_DECIMAL_TO_STRING
When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.
When set to `True`, the serializer `DecimalField` class will return strings instead of `Decimal` objects. When set to `False`, serializers will return `Decimal` objects, which the default JSON encoder will return as floats.
Default: `True`
---
## View names and descriptions
**The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.**
#### VIEW_NAME_FUNCTION
A string representing the function that should be used when generating view names.
This should be a function with the following signature:
view_name(cls, suffix=None)
* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`.
* `suffix`: The optional suffix used when differentiating individual views in a viewset.
Default: `'rest_framework.views.get_view_name'`
#### VIEW_DESCRIPTION_FUNCTION
A string representing the function that should be used when generating view descriptions.
This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support `rst` markup in your view docstrings being output in the browsable API.
This should be a function with the following signature:
view_description(cls, html=False)
* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__`
* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
Default: `'rest_framework.views.get_view_description'`
Version 3.5 (#4525) * Start test case * Added 'requests' test client * Address typos * Graceful fallback if requests is not installed. * Add cookie support * Tests for auth and CSRF * Py3 compat * py3 compat * py3 compat * Add get_requests_client * Added SchemaGenerator.should_include_link * add settings for html cutoff on related fields * Router doesn't work if prefix is blank, though project urls.py handles prefix * Fix Django 1.10 to-many deprecation * Add django.core.urlresolvers compatibility * Update django-filter & django-guardian * Check for empty router prefix; adjust URL accordingly It's easiest to fix this issue after we have made the regex. To try to fix it before would require doing something different for List vs Detail, which means we'd have to know which type of url we're constructing before acting accordingly. * Fix misc django deprecations * Use TOC extension instead of header * Fix deprecations for py3k * Add py3k compatibility to is_simple_callable * Add is_simple_callable tests * Drop python 3.2 support (EOL, Dropped by Django) * schema_renderers= should *set* the renderers, not append to them. * API client (#4424) * Fix release notes * Add note about 'User account is disabled.' vs 'Unable to log in' * Clean up schema generation (#4527) * Handle multiple methods on custom action (#4529) * RequestsClient, CoreAPIClient * exclude_from_schema * Added 'get_schema_view()' shortcut * Added schema descriptions * Better descriptions for schemas * Add type annotation to schema generation * Coerce schema 'pk' in path to actual field name * Deprecations move into assertion errors * Use get_schema_view in tests * Updte CoreJSON media type * Handle schema structure correctly when path prefixs exist. Closes #4401 * Add PendingDeprecation to Router schema generation. * Added SCHEMA_COERCE_PATH_PK and SCHEMA_COERCE_METHOD_NAMES * Renamed and documented 'get_schema_fields' interface.
2016-10-10 15:03:46 +03:00
## HTML Select Field cutoffs
Global settings for [select field cutoffs for rendering relational fields](relations.md#select-field-cutoffs) in the browsable API.
#### HTML_SELECT_CUTOFF
Global setting for the `html_cutoff` value. Must be an integer.
Default: 1000
#### HTML_SELECT_CUTOFF_TEXT
A string representing a global setting for `html_cutoff_text`.
Default: `"More than {count} items..."`
---
2013-03-06 16:19:39 +04:00
## Miscellaneous settings
#### EXCEPTION_HANDLER
A string representing the function that should be used when returning a response for any given exception. If the function returns `None`, a 500 error will be raised.
This setting can be changed to support error responses other than the default `{"detail": "Failure..."}` responses. For example, you can use it to provide API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`.
This should be a function with the following signature:
2014-12-14 17:16:52 +03:00
exception_handler(exc, context)
* `exc`: The exception.
Default: `'rest_framework.views.exception_handler'`
#### NON_FIELD_ERRORS_KEY
A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.
Default: `'non_field_errors'`
2014-01-15 00:34:33 +04:00
#### URL_FIELD_NAME
A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`.
Default: `'url'`
#### NUM_PROXIES
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes.
Default: `None`
[cite]: https://www.python.org/dev/peps/pep-0020/
[rfc4627]: https://www.ietf.org/rfc/rfc4627.txt
2014-09-12 15:40:53 +04:00
[heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses
[strftime]: https://docs.python.org/3/library/time.html#time.strftime