Debian Codegraph @

docs/api-guide/settings.md

raw
1 ---
2 source:
3 - settings.py
4 ---
5
6 # Settings
7
8 > Namespaces are one honking great idea - let's do more of those!
9 >
10 > — [The Zen of Python][cite]
11
12 Configuration for REST framework is all namespaced inside a single Django setting, named `REST_FRAMEWORK`.
13
14 For example your project's `settings.py` file might include something like this:
15
16 REST_FRAMEWORK = {
17 'DEFAULT_RENDERER_CLASSES': [
18 'rest_framework.renderers.JSONRenderer',
19 ],
20 'DEFAULT_PARSER_CLASSES': [
21 'rest_framework.parsers.JSONParser',
22 ]
23 }
24
25 ## Accessing settings
26
27 If you need to access the values of REST framework's API settings in your project,
28 you should use the `api_settings` object. For example.
29
30 from rest_framework.settings import api_settings
31
32 print(api_settings.DEFAULT_AUTHENTICATION_CLASSES)
33
34 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.
35
36 ---
37
38 ## API Reference
39
40 ### API policy settings
41
42 *The following settings control the basic API policies, and are applied to every `APIView` class-based view, or `@api_view` function based view.*
43
44 #### DEFAULT_RENDERER_CLASSES
45
46 A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object.
47
48 Default:
49
50 [
51 'rest_framework.renderers.JSONRenderer',
52 'rest_framework.renderers.BrowsableAPIRenderer',
53 ]
54
55 #### DEFAULT_PARSER_CLASSES
56
57 A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.data` property.
58
59 Default:
60
61 [
62 'rest_framework.parsers.JSONParser',
63 'rest_framework.parsers.FormParser',
64 'rest_framework.parsers.MultiPartParser'
65 ]
66
67 #### DEFAULT_AUTHENTICATION_CLASSES
68
69 A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties.
70
71 Default:
72
73 [
74 'rest_framework.authentication.SessionAuthentication',
75 'rest_framework.authentication.BasicAuthentication'
76 ]
77
78 #### DEFAULT_PERMISSION_CLASSES
79
80 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.
81
82 Default:
83
84 [
85 'rest_framework.permissions.AllowAny',
86 ]
87
88 #### DEFAULT_THROTTLE_CLASSES
89
90 A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
91
92 Default: `[]`
93
94 #### DEFAULT_CONTENT_NEGOTIATION_CLASS
95
96 A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
97
98 Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
99
100 #### DEFAULT_SCHEMA_CLASS
101
102 A view inspector class that will be used for schema generation.
103
104 Default: `'rest_framework.schemas.openapi.AutoSchema'`
105
106 ---
107
108 ### Generic view settings
109
110 *The following settings control the behavior of the generic class-based views.*
111
112 #### DEFAULT_FILTER_BACKENDS
113
114 A list of filter backend classes that should be used for generic filtering.
115 If set to `None` then generic filtering is disabled.
116
117 #### DEFAULT_PAGINATION_CLASS
118
119 The default class to use for queryset pagination. If set to `None`, pagination
120 is disabled by default. See the pagination documentation for further guidance on
121 [setting](pagination.md#setting-the-pagination-style) and
122 [modifying](pagination.md#modifying-the-pagination-style) the pagination style.
123
124 Default: `None`
125
126 #### PAGE_SIZE
127
128 The default page size to use for pagination. If set to `None`, pagination is disabled by default.
129
130 Default: `None`
131
132 #### SEARCH_PARAM
133
134 The name of a query parameter, which can be used to specify the search term used by `SearchFilter`.
135
136 Default: `search`
137
138 #### ORDERING_PARAM
139
140 The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`.
141
142 Default: `ordering`
143
144 ---
145
146 ### Versioning settings
147
148 #### DEFAULT_VERSION
149
150 The value that should be used for `request.version` when no versioning information is present.
151
152 Default: `None`
153
154 #### ALLOWED_VERSIONS
155
156 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.
157
158 Default: `None`
159
160 #### VERSION_PARAM
161
162 The string that should used for any versioning parameters, such as in the media type or URL query parameters.
163
164 Default: `'version'`
165
166 #### DEFAULT_VERSIONING_CLASS
167
168 The default versioning scheme to use.
169
170 Default: `None`
171
172 ---
173
174 ### Authentication settings
175
176 *The following settings control the behavior of unauthenticated requests.*
177
178 #### UNAUTHENTICATED_USER
179
180 The class that should be used to initialize `request.user` for unauthenticated requests.
181 (If removing authentication entirely, e.g. by removing `django.contrib.auth` from
182 `INSTALLED_APPS`, set `UNAUTHENTICATED_USER` to `None`.)
183
184 Default: `django.contrib.auth.models.AnonymousUser`
185
186 #### UNAUTHENTICATED_TOKEN
187
188 The class that should be used to initialize `request.auth` for unauthenticated requests.
189
190 Default: `None`
191
192 ---
193
194 ### Test settings
195
196 *The following settings control the behavior of APIRequestFactory and APIClient*
197
198 #### TEST_REQUEST_DEFAULT_FORMAT
199
200 The default format that should be used when making test requests.
201
202 This should match up with the format of one of the renderer classes in the `TEST_REQUEST_RENDERER_CLASSES` setting.
203
204 Default: `'multipart'`
205
206 #### TEST_REQUEST_RENDERER_CLASSES
207
208 The renderer classes that are supported when building test requests.
209
210 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')`
211
212 Default:
213
214 [
215 'rest_framework.renderers.MultiPartRenderer',
216 'rest_framework.renderers.JSONRenderer'
217 ]
218
219 ---
220
221 ### Schema generation controls
222
223 #### SCHEMA_COERCE_PATH_PK
224
225 If set, this maps the `'pk'` identifier in the URL conf onto the actual field
226 name when generating a schema path parameter. Typically this will be `'id'`.
227 This gives a more suitable representation as "primary key" is an implementation
228 detail, whereas "identifier" is a more general concept.
229
230 Default: `True`
231
232 #### SCHEMA_COERCE_METHOD_NAMES
233
234 If set, this is used to map internal viewset method names onto external action
235 names used in the schema generation. This allows us to generate names that
236 are more suitable for an external representation than those that are used
237 internally in the codebase.
238
239 Default: `{'retrieve': 'read', 'destroy': 'delete'}`
240
241 ---
242
243 ### Content type controls
244
245 #### URL_FORMAT_OVERRIDE
246
247 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.
248
249 For example: `http://example.com/organizations/?format=csv`
250
251 If the value of this setting is `None` then URL format overrides will be disabled.
252
253 Default: `'format'`
254
255 #### FORMAT_SUFFIX_KWARG
256
257 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.
258
259 For example: `http://example.com/organizations.csv/`
260
261 Default: `'format'`
262
263 ---
264
265 ### Date and time formatting
266
267 *The following settings are used to control how date and time representations may be parsed and rendered.*
268
269 #### DATETIME_FORMAT
270
271 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.
272
273 May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
274
275 Default: `'iso-8601'`
276
277 #### DATETIME_INPUT_FORMATS
278
279 A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields.
280
281 May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
282
283 Default: `['iso-8601']`
284
285 #### DATE_FORMAT
286
287 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.
288
289 May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
290
291 Default: `'iso-8601'`
292
293 #### DATE_INPUT_FORMATS
294
295 A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields.
296
297 May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
298
299 Default: `['iso-8601']`
300
301 #### TIME_FORMAT
302
303 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.
304
305 May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
306
307 Default: `'iso-8601'`
308
309 #### TIME_INPUT_FORMATS
310
311 A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields.
312
313 May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
314
315 Default: `['iso-8601']`
316
317
318 #### DURATION_FORMAT
319
320 Indicates the default format that should be used for rendering the output of `DurationField` serializer fields. If `None`, then `DurationField` serializer fields will return Python `timedelta` objects, and the duration encoding will be determined by the renderer.
321
322 May be any of `None`, `'iso-8601'` or `'django'` (the format accepted by `django.utils.dateparse.parse_duration`).
323
324 Default: `'django'`
325
326 ---
327
328 ### Encodings
329
330 #### UNICODE_JSON
331
332 When set to `True`, JSON responses will allow unicode characters in responses. For example:
333
334 {"unicode black star":"★"}
335
336 When set to `False`, JSON responses will escape non-ascii characters, like so:
337
338 {"unicode black star":"\u2605"}
339
340 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.
341
342 Default: `True`
343
344 #### COMPACT_JSON
345
346 When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example:
347
348 {"is_admin":false,"email":"jane@example"}
349
350 When set to `False`, JSON responses will return slightly more verbose representations, like so:
351
352 {"is_admin": false, "email": "jane@example"}
353
354 The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json].
355
356 Default: `True`
357
358 #### STRICT_JSON
359
360 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.
361
362 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.
363
364 Default: `True`
365
366 #### COERCE_DECIMAL_TO_STRING
367
368 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.
369
370 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.
371
372 Default: `True`
373
374 #### COERCE_BIGINT_TO_STRING
375
376 When returning biginteger objects in API representations that do not support numbers up to 2^64, it is best to return the value as a string. This avoids the loss of precision that occurs with biginteger implementations.
377
378 When set to `True`, the serializer `BigIntegerField` class (by default) will return strings instead of `BigInteger` objects. When set to `False`, serializers will return `BigInteger` objects, which the default JSON encoder will return as numbers.
379
380 Default: `False`
381
382 ---
383
384 ### View names and descriptions
385
386 **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.**
387
388 #### VIEW_NAME_FUNCTION
389
390 A string representing the function that should be used when generating view names.
391
392 This should be a function with the following signature:
393
394 view_name(self)
395
396 * `self`: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `self.__class__.__name__`.
397
398 If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
399
400 * `name`: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided.
401 * `suffix`: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to `name`.
402 * `detail`: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view.
403
404 Default: `'rest_framework.views.get_view_name'`
405
406 #### VIEW_DESCRIPTION_FUNCTION
407
408 A string representing the function that should be used when generating view descriptions.
409
410 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.
411
412 This should be a function with the following signature:
413
414 view_description(self, html=False)
415
416 * `self`: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing `self.__class__.__doc__`
417 * `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
418
419 If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments:
420
421 * `description`: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset `action`s, and should be used as-is.
422
423 Default: `'rest_framework.views.get_view_description'`
424
425 ### HTML Select Field cutoffs
426
427 Global settings for [select field cutoffs for rendering relational fields](relations.md#select-field-cutoffs) in the browsable API.
428
429 #### HTML_SELECT_CUTOFF
430
431 Global setting for the `html_cutoff` value. Must be an integer.
432
433 Default: 1000
434
435 #### HTML_SELECT_CUTOFF_TEXT
436
437 A string representing a global setting for `html_cutoff_text`.
438
439 Default: `"More than {count} items..."`
440
441 ---
442
443 ### Miscellaneous settings
444
445 #### EXCEPTION_HANDLER
446
447 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.
448
449 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": ""} ...]}`.
450
451 This should be a function with the following signature:
452
453 exception_handler(exc, context)
454
455 * `exc`: The exception.
456
457 Default: `'rest_framework.views.exception_handler'`
458
459 #### NON_FIELD_ERRORS_KEY
460
461 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.
462
463 Default: `'non_field_errors'`
464
465 #### LIST_SERIALIZER_ERRORS_AS_DICT
466
467 Controls the format of per-item validation errors produced by `ListSerializer`, including serializers instantiated with `many=True`.
468
469 When set to `True`, errors are returned as a dictionary keyed by the indexes of invalid items. Valid items are omitted from the dictionary. This format was introduced in REST framework 3.18.0.
470
471 When set to `False`, errors are returned in the list-based format used before REST framework 3.18, with one entry for each input item and an empty dictionary for each valid item. This format is deprecated and will be removed in REST framework 3.20.
472
473 Default: `True`
474
475 #### URL_FIELD_NAME
476
477 A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`.
478
479 Default: `'url'`
480
481 #### NUM_PROXIES
482
483 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.
484
485 Default: `None`
486
487 [cite]: https://www.python.org/dev/peps/pep-0020/
488 [rfc4627]: https://www.ietf.org/rfc/rfc4627.txt
489 [heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses
490 [strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes