Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow suppressing context warnings #28

Merged
merged 1 commit into from
Mar 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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