Warning: I'm quite sure this is not a best practice, but this snippet has proven being very useful to me. Handle with care. I also wonder about the impact on performance, while I didn't notice any slowdown on a very small app of mine.
Idea is to expose project settings to template request context through a context processor, and _doc_ should be self-explanatory.
Of course, if you know a better way to achieve the purpose, please tell in the comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # in context_processor.py
import settings
def settings_context(request):
"""Exposes somewhat filtered project settings in a `project_settings` key
of the request context, so you can use stuff like this in templates:
{% if project_settings.DEBUG and project_settings.GOOGLE_MAP_API_KEY %}
<p>Dude, Google API key is {{ project_settings.GOOGLE_MAP_API_KEY }}.</p>
{% endif %}
"""
_settings = {}
for setting in dir(settings):
if setting.startswith('__'):
continue
try:
setting_value = getattr(settings, setting)
if type(setting_value) in [bool, str, int, float, tuple, list, dict]:
_settings[setting] = setting_value
except:
pass
return {'project_settings': _settings}
# in settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
# ...
'myapp.context_processors.settings_context',
# ...
)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
django.conf only wraps projects settings, so You can do it in simpler way:
regards.
#
Sure, this is by far better, thanks!
#
Please login first before commenting.