From 9c7fda414211d9dcc71678e72c349c1d0038f85b Mon Sep 17 00:00:00 2001 From: Stefan Schindler Date: Fri, 30 Aug 2019 08:52:02 +0200 Subject: [PATCH] Allow setting trim_whitespace globally through API settings --- docs/api-guide/fields.md | 4 ++-- rest_framework/fields.py | 2 +- rest_framework/settings.py | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 19abb0424..c08da159f 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -158,12 +158,12 @@ A text representation. Optionally validates the text to be shorter than `max_len Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`. -**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)` +**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=api_settings.TRIM_WHITESPACE)` - `max_length` - Validates that the input contains no more than this number of characters. - `min_length` - Validates that the input contains no fewer than this number of characters. - `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. -- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`. +- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to the `TRIM_WHITESPACE` settings key which is `True` by default. The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 0be6a7c12..ecc666530 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -768,7 +768,7 @@ class CharField(Field): def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) - self.trim_whitespace = kwargs.pop('trim_whitespace', True) + self.trim_whitespace = kwargs.pop('trim_whitespace', api_settings.TRIM_WHITESPACE) self.max_length = kwargs.pop('max_length', None) self.min_length = kwargs.pop('min_length', None) super().__init__(**kwargs) diff --git a/rest_framework/settings.py b/rest_framework/settings.py index c4c0e7939..ce4f3b20a 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -113,6 +113,7 @@ DEFAULTS = { 'STRICT_JSON': True, 'COERCE_DECIMAL_TO_STRING': True, 'UPLOADED_FILES_USE_URL': True, + 'TRIM_WHITESPACE': True, # Browseable API 'HTML_SELECT_CUTOFF': 1000,