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

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


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 filedef 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 renderdef 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 find the simplest approach being a single custom template tag:

from django import templatefrom django.conf import settingsregister = template.Library()# settings value@register.simple_tagdef settings_value(name):    return getattr(settings, name, "")

Usage:

{% settings_value "LANGUAGE_CODE" %}


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 the render_to_response shortcut function. Here's an example of each case:

from django.shortcuts import render_to_responsefrom django.template import RequestContextfrom django.views.generic.simple import direct_to_templatedef my_generic_view(request, template='my_template.html'):    return direct_to_template(request, template)def more_custom_view(request, template='my_template.html'):    return render_to_response(template, {}, context_instance=RequestContext(request))

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:

from django.conf import settingsfrom django.shortcuts import render_to_responsedef my_view_function(request, template='my_template.html'):    context = {'favorite_color': settings.FAVORITE_COLOR}    return render_to_response(template, context)

Now you can access settings.FAVORITE_COLOR on your template as {{ favorite_color }}.