[django] Can I access constants in settings.py from templates in Django?

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?

This question is related to django django-templates django-settings

The answer is


I found this to be the simplest approach for Django 1.3:

  1. views.py

    from local_settings import BASE_URL
    
    def root(request):
        return render_to_response('hero.html', {'BASE_URL': BASE_URL})
    
  2. hero.html

    var BASE_URL = '{{ JS_BASE_URL }}';
    

Both IanSR and bchhun suggested overriding TEMPLATE_CONTEXT_PROCESSORS in the settings. Be aware that this setting has a default that can cause some screwy things if you override it without re-setting the defaults. The defaults have also changed in recent versions of Django.

https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors

The default TEMPLATE_CONTEXT_PROCESSORS :

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")

Check out django-settings-export (disclaimer: I'm the author of this project).

For example...

$ pip install django-settings-export

settings.py

TEMPLATES = [
    {
        'OPTIONS': {
            'context_processors': [
                'django_settings_export.settings_export',
            ],
        },
    },
]

MY_CHEESE = 'Camembert';

SETTINGS_EXPORT = [
    'MY_CHEESE',
]

template.html

<script>var MY_CHEESE = '{{ settings.MY_CHEESE }}';</script>

If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file
    
    def admin_media(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
    
  2. add your context processor to your settings.py file:

    TEMPLATES = [{
        # whatever comes before
        'OPTIONS': {
            'context_processors': [
                # whatever comes before
                "your_app.context_processors.admin_media",
            ],
        }
    }]
    
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render
    
    def my_view(request):
        return render(request, "index.html")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    

I like Berislav's solution, because on simple sites, it is clean and effective. What I do NOT like is exposing all the settings constants willy-nilly. So what I ended up doing was this:

from django import template
from django.conf import settings

register = template.Library()

ALLOWABLE_VALUES = ("CONSTANT_NAME_1", "CONSTANT_NAME_2",)

# settings value
@register.simple_tag
def settings_value(name):
    if name in ALLOWABLE_VALUES:
        return getattr(settings, name, '')
    return ''

Usage:

{% settings_value "CONSTANT_NAME_1" %}

This protects any constants that you have not named from use in the template, and if you wanted to get really fancy, you could set a tuple in the settings, and create more than one template tag for different pages, apps or areas, and simply combine a local tuple with the settings tuple as needed, then do the list comprehension to see if the value is acceptable.
I agree, on a complex site, this is a bit simplistic, but there are values that would be nice to have universally in templates, and this seems to work nicely. Thanks to Berislav for the original idea!


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:

Custom tags folder structure

In the custom_tags.py create a custom tag function that provides access to an arbitrary key in the settings constant:

from django import template
from django.conf import settings

register = template.Library()

@register.simple_tag
def get_setting(name):
    return getattr(settings, name, "")

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:

{% load custom_tags %}

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:

{% get_setting "BUILD_VERSION" %}

This solution will not work with arrays, but if you need that you might be putting to much logic in your templates.

Note: A more clean and failsafe solution would probably be to make a custom context processor where you add the settings you need to a context available to all templates. This way you reduce the risk of outputting sensitive settings in your templates by mistake.


Another way to do this is to create a custom template tag which can let you fish values out of the settings.

@register.tag
def value_from_settings(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, var = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    return ValueFromSettings(var)

class ValueFromSettings(template.Node):
    def __init__(self, var):
        self.arg = template.Variable(var)
    def render(self, context):        
        return settings.__getattr__(str(self.arg))

You can then use:

{% value_from_settings "FQDN" %}

to print it on any page, without jumping through context-processor hoops.


I found this to be the simplest approach for Django 1.3:

  1. views.py

    from local_settings import BASE_URL
    
    def root(request):
        return render_to_response('hero.html', {'BASE_URL': BASE_URL})
    
  2. hero.html

    var BASE_URL = '{{ JS_BASE_URL }}';
    

The example above from bchhun is nice except that you need to explicitly build your context dictionary from settings.py. Below is an UNTESTED example of how you could auto-build the context dictionary from all upper-case attributes of settings.py (re: "^[A-Z0-9_]+$").

At the end of settings.py:

_context = {} 
local_context = locals()
for (k,v) in local_context.items():
    if re.search('^[A-Z0-9_]+$',k):
        _context[k] = str(v)

def settings_context(context):
    return _context

TEMPLATE_CONTEXT_PROCESSORS = (
...
'myproject.settings.settings_context',
...
)

I improved chrisdew's answer (to create your own tag) a little bit.

First, create the file yourapp/templatetags/value_from_settings.py in which you define your own new tag value_from_settings:

from django.template import TemplateSyntaxError, Variable, Node, Variable, Library
from yourapp import settings

register = Library()
# I found some tricks in URLNode and url from defaulttags.py:
# https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py
@register.tag
def value_from_settings(parser, token):
  bits = token.split_contents()
  if len(bits) < 2:
    raise TemplateSyntaxError("'%s' takes at least one " \
      "argument (settings constant to retrieve)" % bits[0])
  settingsvar = bits[1]
  settingsvar = settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar
  asvar = None
  bits = bits[2:]
  if len(bits) >= 2 and bits[-2] == 'as':
    asvar = bits[-1]
    bits = bits[:-2]
  if len(bits):
    raise TemplateSyntaxError("'value_from_settings' didn't recognise " \
      "the arguments '%s'" % ", ".join(bits))
  return ValueFromSettings(settingsvar, asvar)

class ValueFromSettings(Node):
  def __init__(self, settingsvar, asvar):
    self.arg = Variable(settingsvar)
    self.asvar = asvar
  def render(self, context):
    ret_val = getattr(settings,str(self.arg))
    if self.asvar:
      context[self.asvar] = ret_val
      return ''
    else:
      return ret_val

You can use this tag in your Template via:

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" %}

or via

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" as my_fqdn %}

The advantage of the as ... notation is that this makes it easy to use in blocktrans blocks via a simple {{my_fqdn}}.


If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file
    
    def admin_media(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
    
  2. add your context processor to your settings.py file:

    TEMPLATES = [{
        # whatever comes before
        'OPTIONS': {
            'context_processors': [
                # whatever comes before
                "your_app.context_processors.admin_media",
            ],
        }
    }]
    
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render
    
    def my_view(request):
        return render(request, "index.html")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    

Another way to do this is to create a custom template tag which can let you fish values out of the settings.

@register.tag
def value_from_settings(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, var = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    return ValueFromSettings(var)

class ValueFromSettings(template.Node):
    def __init__(self, var):
        self.arg = template.Variable(var)
    def render(self, context):        
        return settings.__getattr__(str(self.arg))

You can then use:

{% value_from_settings "FQDN" %}

to print it on any page, without jumping through context-processor hoops.


I find the simplest approach being a single custom template tag:

from django import template
from django.conf import settings

register = template.Library()

# settings value
@register.simple_tag
def settings_value(name):
    return getattr(settings, name, "")

Usage:

{% settings_value "LANGUAGE_CODE" %}

I improved chrisdew's answer (to create your own tag) a little bit.

First, create the file yourapp/templatetags/value_from_settings.py in which you define your own new tag value_from_settings:

from django.template import TemplateSyntaxError, Variable, Node, Variable, Library
from yourapp import settings

register = Library()
# I found some tricks in URLNode and url from defaulttags.py:
# https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py
@register.tag
def value_from_settings(parser, token):
  bits = token.split_contents()
  if len(bits) < 2:
    raise TemplateSyntaxError("'%s' takes at least one " \
      "argument (settings constant to retrieve)" % bits[0])
  settingsvar = bits[1]
  settingsvar = settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar
  asvar = None
  bits = bits[2:]
  if len(bits) >= 2 and bits[-2] == 'as':
    asvar = bits[-1]
    bits = bits[:-2]
  if len(bits):
    raise TemplateSyntaxError("'value_from_settings' didn't recognise " \
      "the arguments '%s'" % ", ".join(bits))
  return ValueFromSettings(settingsvar, asvar)

class ValueFromSettings(Node):
  def __init__(self, settingsvar, asvar):
    self.arg = Variable(settingsvar)
    self.asvar = asvar
  def render(self, context):
    ret_val = getattr(settings,str(self.arg))
    if self.asvar:
      context[self.asvar] = ret_val
      return ''
    else:
      return ret_val

You can use this tag in your Template via:

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" %}

or via

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" as my_fqdn %}

The advantage of the as ... notation is that this makes it easy to use in blocktrans blocks via a simple {{my_fqdn}}.


If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file
    
    def admin_media(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
    
  2. add your context processor to your settings.py file:

    TEMPLATES = [{
        # whatever comes before
        'OPTIONS': {
            'context_processors': [
                # whatever comes before
                "your_app.context_processors.admin_media",
            ],
        }
    }]
    
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render
    
    def my_view(request):
        return render(request, "index.html")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    

Add this code to a file called context_processors.py:

from django.conf import settings as django_settings


def settings(request):
    return {
        'settings': django_settings,
    }

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 in TEMPLATES.

(You can see for example settings/base.py and context_processors.py).

Then you can use the specific setting in any template code. For example:

{% if settings.SITE_ID == settings.SPEEDY_MATCH_SITE_ID %}

Update: The code above exposes all the settings to templates, including sensitive information such as your SECRET_KEY. A hacker might abuse this feature to display such information in the templates. If you want to expose only specific settings to the templates, use this code instead:

def settings(request):
    settings_in_templates = {}
    for attr in ["SITE_ID", ...]: # Write here the settings you want to expose to the templates.
        if (hasattr(django_settings, attr)):
            settings_in_templates[attr] = getattr(django_settings, attr)
    return {
        'settings': settings_in_templates,
    }

Both IanSR and bchhun suggested overriding TEMPLATE_CONTEXT_PROCESSORS in the settings. Be aware that this setting has a default that can cause some screwy things if you override it without re-setting the defaults. The defaults have also changed in recent versions of Django.

https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors

The default TEMPLATE_CONTEXT_PROCESSORS :

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")

If we were to compare context vs. template tags on a single variable, then knowing the more efficient option could be benificial. However, you might be better off to dip into the settings only from templates that need that variable. In that case it doesn't make sense to pass the variable into all templates. But if you are sending the variable into a common template such as the base.html template, Then it would not matter as the base.html template is rendered on every request, so you can use either methods.

If you decide to go with the template tags option, then use the following code as it allows you to pass a default value in, just in case the variable in-question was undefined.

Example: get_from_settings my_variable as my_context_value

Example: get_from_settings my_variable my_default as my_context_value

class SettingsAttrNode(Node):
    def __init__(self, variable, default, as_value):
        self.variable = getattr(settings, variable, default)
        self.cxtname = as_value

    def render(self, context):
        context[self.cxtname] = self.variable
        return ''


def get_from_setting(parser, token):
    as_value = variable = default = ''
    bits = token.contents.split()
    if len(bits) == 4 and bits[2] == 'as':
        variable = bits[1]
        as_value = bits[3]
    elif len(bits) == 5 and bits[3] == 'as':
        variable     = bits[1]
        default  = bits[2]
        as_value = bits[4]
    else:
        raise TemplateSyntaxError, "usage: get_from_settings variable default as value " \
                "OR: get_from_settings variable as value"

    return SettingsAttrNode(variable=variable, default=default, as_value=as_value)

get_from_setting = register.tag(get_from_setting)

If using a class-based view:

#
# in settings.py
#
YOUR_CUSTOM_SETTING = 'some value'

#
# in views.py
#
from django.conf import settings #for getting settings vars

class YourView(DetailView): #assuming DetailView; whatever though

    # ...

    def get_context_data(self, **kwargs):

        context = super(YourView, self).get_context_data(**kwargs)
        context['YOUR_CUSTOM_SETTING'] = settings.YOUR_CUSTOM_SETTING

        return context

#
# in your_template.html, reference the setting like any other context variable
#
{{ YOUR_CUSTOM_SETTING }}

Add this code to a file called context_processors.py:

from django.conf import settings as django_settings


def settings(request):
    return {
        'settings': django_settings,
    }

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 in TEMPLATES.

(You can see for example settings/base.py and context_processors.py).

Then you can use the specific setting in any template code. For example:

{% if settings.SITE_ID == settings.SPEEDY_MATCH_SITE_ID %}

Update: The code above exposes all the settings to templates, including sensitive information such as your SECRET_KEY. A hacker might abuse this feature to display such information in the templates. If you want to expose only specific settings to the templates, use this code instead:

def settings(request):
    settings_in_templates = {}
    for attr in ["SITE_ID", ...]: # Write here the settings you want to expose to the templates.
        if (hasattr(django_settings, attr)):
            settings_in_templates[attr] = getattr(django_settings, attr)
    return {
        'settings': settings_in_templates,
    }

If someone finds this question like I did, then I'll post my solution which works on Django 2.0:

This tag assigns some settings.py variable value to template's variable:

Usage: {% get_settings_value template_var "SETTINGS_VAR" %}

app/templatetags/my_custom_tags.py:

from django import template
from django.conf import settings

register = template.Library()

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def render(self, context):
        context[self.name] = getattr(settings, self.value.resolve(context, True), "")
        return ''

@register.tag('get_settings_value')
def do_assign(parser, token):
    bits = token.split_contents()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

Your template:

{% load my_custom_tags %}

# Set local template variable:
{% get_settings_value settings_debug "DEBUG" %}

# Output settings_debug variable:
{{ settings_debug }}

# Use variable in if statement:
{% if settings_debug %}
... do something ...
{% else %}
... do other stuff ...
{% endif %}

See Django's documentation how to create custom template tags here: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/


If using a class-based view:

#
# in settings.py
#
YOUR_CUSTOM_SETTING = 'some value'

#
# in views.py
#
from django.conf import settings #for getting settings vars

class YourView(DetailView): #assuming DetailView; whatever though

    # ...

    def get_context_data(self, **kwargs):

        context = super(YourView, self).get_context_data(**kwargs)
        context['YOUR_CUSTOM_SETTING'] = settings.YOUR_CUSTOM_SETTING

        return context

#
# in your_template.html, reference the setting like any other context variable
#
{{ YOUR_CUSTOM_SETTING }}

I like Berislav's solution, because on simple sites, it is clean and effective. What I do NOT like is exposing all the settings constants willy-nilly. So what I ended up doing was this:

from django import template
from django.conf import settings

register = template.Library()

ALLOWABLE_VALUES = ("CONSTANT_NAME_1", "CONSTANT_NAME_2",)

# settings value
@register.simple_tag
def settings_value(name):
    if name in ALLOWABLE_VALUES:
        return getattr(settings, name, '')
    return ''

Usage:

{% settings_value "CONSTANT_NAME_1" %}

This protects any constants that you have not named from use in the template, and if you wanted to get really fancy, you could set a tuple in the settings, and create more than one template tag for different pages, apps or areas, and simply combine a local tuple with the settings tuple as needed, then do the list comprehension to see if the value is acceptable.
I agree, on a complex site, this is a bit simplistic, but there are values that would be nice to have universally in templates, and this seems to work nicely. Thanks to Berislav for the original idea!


The example above from bchhun is nice except that you need to explicitly build your context dictionary from settings.py. Below is an UNTESTED example of how you could auto-build the context dictionary from all upper-case attributes of settings.py (re: "^[A-Z0-9_]+$").

At the end of settings.py:

_context = {} 
local_context = locals()
for (k,v) in local_context.items():
    if re.search('^[A-Z0-9_]+$',k):
        _context[k] = str(v)

def settings_context(context):
    return _context

TEMPLATE_CONTEXT_PROCESSORS = (
...
'myproject.settings.settings_context',
...
)

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:

Custom tags folder structure

In the custom_tags.py create a custom tag function that provides access to an arbitrary key in the settings constant:

from django import template
from django.conf import settings

register = template.Library()

@register.simple_tag
def get_setting(name):
    return getattr(settings, name, "")

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:

{% load custom_tags %}

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:

{% get_setting "BUILD_VERSION" %}

This solution will not work with arrays, but if you need that you might be putting to much logic in your templates.

Note: A more clean and failsafe solution would probably be to make a custom context processor where you add the settings you need to a context available to all templates. This way you reduce the risk of outputting sensitive settings in your templates by mistake.


If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file
    
    def admin_media(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
    
  2. add your context processor to your settings.py file:

    TEMPLATES = [{
        # whatever comes before
        'OPTIONS': {
            'context_processors': [
                # whatever comes before
                "your_app.context_processors.admin_media",
            ],
        }
    }]
    
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render
    
    def my_view(request):
        return render(request, "index.html")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    

If we were to compare context vs. template tags on a single variable, then knowing the more efficient option could be benificial. However, you might be better off to dip into the settings only from templates that need that variable. In that case it doesn't make sense to pass the variable into all templates. But if you are sending the variable into a common template such as the base.html template, Then it would not matter as the base.html template is rendered on every request, so you can use either methods.

If you decide to go with the template tags option, then use the following code as it allows you to pass a default value in, just in case the variable in-question was undefined.

Example: get_from_settings my_variable as my_context_value

Example: get_from_settings my_variable my_default as my_context_value

class SettingsAttrNode(Node):
    def __init__(self, variable, default, as_value):
        self.variable = getattr(settings, variable, default)
        self.cxtname = as_value

    def render(self, context):
        context[self.cxtname] = self.variable
        return ''


def get_from_setting(parser, token):
    as_value = variable = default = ''
    bits = token.contents.split()
    if len(bits) == 4 and bits[2] == 'as':
        variable = bits[1]
        as_value = bits[3]
    elif len(bits) == 5 and bits[3] == 'as':
        variable     = bits[1]
        default  = bits[2]
        as_value = bits[4]
    else:
        raise TemplateSyntaxError, "usage: get_from_settings variable default as value " \
                "OR: get_from_settings variable as value"

    return SettingsAttrNode(variable=variable, default=default, as_value=as_value)

get_from_setting = register.tag(get_from_setting)

I find the simplest approach being a single custom template tag:

from django import template
from django.conf import settings

register = template.Library()

# settings value
@register.simple_tag
def settings_value(name):
    return getattr(settings, name, "")

Usage:

{% settings_value "LANGUAGE_CODE" %}

Check out django-settings-export (disclaimer: I'm the author of this project).

For example...

$ pip install django-settings-export

settings.py

TEMPLATES = [
    {
        'OPTIONS': {
            'context_processors': [
                'django_settings_export.settings_export',
            ],
        },
    },
]

MY_CHEESE = 'Camembert';

SETTINGS_EXPORT = [
    'MY_CHEESE',
]

template.html

<script>var MY_CHEESE = '{{ settings.MY_CHEESE }}';</script>

If someone finds this question like I did, then I'll post my solution which works on Django 2.0:

This tag assigns some settings.py variable value to template's variable:

Usage: {% get_settings_value template_var "SETTINGS_VAR" %}

app/templatetags/my_custom_tags.py:

from django import template
from django.conf import settings

register = template.Library()

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def render(self, context):
        context[self.name] = getattr(settings, self.value.resolve(context, True), "")
        return ''

@register.tag('get_settings_value')
def do_assign(parser, token):
    bits = token.split_contents()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

Your template:

{% load my_custom_tags %}

# Set local template variable:
{% get_settings_value settings_debug "DEBUG" %}

# Output settings_debug variable:
{{ settings_debug }}

# Use variable in if statement:
{% if settings_debug %}
... do something ...
{% else %}
... do other stuff ...
{% endif %}

See Django's documentation how to create custom template tags here: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/


Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to django-templates

Django - Did you forget to register or load this tag? How to add url parameters to Django template url tag? bootstrap 3 wrap text content within div for horizontal alignment Django, creating a custom 500/404 error page How can I get the username of the logged-in user in Django? Does Python have a toString() equivalent, and can I convert a db.Model element to String? How do I call a Django function on button click? What is the equivalent of "none" in django templates? Django - iterate number in for loop of a template Django -- Template tag in {% if %} block

Examples related to django-settings

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings sqlite3.OperationalError: unable to open database file How to set up a PostgreSQL database in Django Django - after login, redirect user to his custom page --> mysite.com/username Can I access constants in settings.py from templates in Django?