I have some stuff in settings.py that I'd like to be able to access from a template, but I can't figure out how to do it. I already tried
{{CONSTANT_NAME}}
but that doesn't seem to work. Is this possible?
I have some stuff in settings.py that I'd like to be able to access from a template, but I can't figure out how to do it. I already tried
{{CONSTANT_NAME}}
but that doesn't seem to work. Is this possible?
Another way to do this is to create a custom template tag which can let you fish values out of the settings.
You can then use:
to print it on any page, without jumping through context-processor hoops.
I find the simplest approach being a single template tag:
Usage:
Adding an answer with complete instructions for creating a custom template tag that solves this, with Django 2.0+
In your app-folder, create a folder called templatetags. In it, create __init__.py and custom_tags.py:
In the custom_tags.py create a custom tag function that provides access to an arbitrary key in the settings constant:
To understand this code I recommend reading the section on simple tags in the Django docs.
Then, you need to make Django aware of this (and any additional) custom tag by loading this file in any template where you will use it. Just like you need to load the built in static tag:
With it loaded it can be used just like any other tag, just supply the specific setting you need returned. So if you have a BUILD_VERSION variable in your settings:
This solution will not work with arrays, but if you need that you might be putting to much logic in your templates.
Add this code to a file called
context_processors.py
:And then, in your settings file, include a path such as
'speedy.core.base.context_processors.settings'
(with your app name and path) in the'context_processors'
settings inTEMPLATES
.(You can see for example https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/core/settings/base.py and https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/core/base/context_processors.py).
Django provides access to certain, frequently-used settings constants to the template such as
settings.MEDIA_URL
and some of the language settings if you use django's built in generic views or pass in a context instance keyword argument in therender_to_response
shortcut function. Here's an example of each case:These views will both have several frequently used settings like
settings.MEDIA_URL
available to the template as{{ MEDIA_URL }}
, etc.If you're looking for access to other constants in the settings, then simply unpack the constants you want and add them to the context dictionary you're using in your view function, like so:
Now you can access
settings.FAVORITE_COLOR
on your template as{{ favorite_color }}
.If using a class-based view: