Skip to content

Commit

Permalink
Allow suppressing context warnings (#28)
Browse files Browse the repository at this point in the history
Fixes #27.
  • Loading branch information
dbrgn authored Mar 1, 2019
1 parent 22ae0ec commit ef1e095
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Possible log types:

## [Unreleased]

- ...
- [changed] Allow suppressing context warnings (#27)

## [0.3.0] - 2018-03-03

Expand Down
21 changes: 21 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/dbrgn/drf-dynamic-fields/issues/27>`_).
In that case, you can silence the warning through ``settings.py``:

.. sourcecode:: python

DRF_DYNAMIC_FIELDS = {
'SUPPRESS_CONTEXT_WARNING': True,
}

Scope
-----

Expand Down
7 changes: 6 additions & 1 deletion drf_dynamic_fields/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"""
import warnings

from django.conf import settings


class DynamicFieldsMixin(object):
"""
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit ef1e095

Please sign in to comment.