From ef1e0954c30d19c42bfbfe8f4628079792b0f73e Mon Sep 17 00:00:00 2001 From: Danilo Bargen Date: Fri, 1 Mar 2019 16:04:01 +0100 Subject: [PATCH] Allow suppressing context warnings (#28) Fixes #27. --- CHANGELOG.md | 2 +- README.rst | 21 +++++++++++++++++++++ drf_dynamic_fields/__init__.py | 7 ++++++- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bf0beb..dba6d08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ Possible log types: ## [Unreleased] - - ... + - [changed] Allow suppressing context warnings (#27) ## [0.3.0] - 2018-03-03 diff --git a/README.rst b/README.rst index 04dafb9..94e526b 100644 --- a/README.rst +++ b/README.rst @@ -137,6 +137,27 @@ pass in the request through the context: serializer = EventSerializer(events, many=True, context={'request': request}) +Warnings +-------- + +If the request context does not have access to the request, a warning is +emitted:: + + UserWarning: Context does not have access to request. + +First, make sure that you are passing the request to the serializer context (see +"Usage" section). + +There are some cases (e.g. nested serializers) where you cannot get rid of the +warning that way (see `issue 27 `_). +In that case, you can silence the warning through ``settings.py``: + +.. sourcecode:: python + + DRF_DYNAMIC_FIELDS = { + 'SUPPRESS_CONTEXT_WARNING': True, + } + Scope ----- diff --git a/drf_dynamic_fields/__init__.py b/drf_dynamic_fields/__init__.py index e19124d..73ae6cf 100644 --- a/drf_dynamic_fields/__init__.py +++ b/drf_dynamic_fields/__init__.py @@ -3,6 +3,8 @@ """ import warnings +from django.conf import settings + class DynamicFieldsMixin(object): """ @@ -36,7 +38,10 @@ def fields(self): try: request = self.context['request'] except KeyError: - warnings.warn('Context does not have access to request') + conf = getattr(settings, 'DRF_DYNAMIC_FIELDS', {}) + if not conf.get('SUPPRESS_CONTEXT_WARNING', False) is True: + warnings.warn('Context does not have access to request. ' + 'See README for more information.') return fields # NOTE: drf test framework builds a request object where the query