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

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.

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_response from django. Template import RequestContext from django.views.generic. Simple import direct_to_template def 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 settings from django. Shortcuts import render_to_response def 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 }}.

6 It's worth noting that the specific values added by using a RequestContext is dependent on the value of TEMPLATE_CONTEXT_PROCESSORS. Thus if you want additional values passed in everywhere, just write your own context processor and add it to TEMPLATE_CONTEXT_PROCESSORS. – Carl Meyer Jan 26 '09 at 19:12 A point on consistency, in the generic views, and many of the core and contrib apps, additional context is called extra_context, and very often it is included in the view's arguments.

– Soviut Jun 1 '09 at 1:33 "Django provides access to certain, frequently-used settings constants to the template such as settings. MEDIA_URL". This doesn't appear to work in Django 1.3, although I'm probably using it wrong.Is there any documentation for this feature?

– SystemParadox Oct 28 at 10:46.

If it's a value you'd like to have for every request & template, using a context processor is more appropriate. Here's how: 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(context): # return the value you want as a dictionnary. You may add multiple values in there.

Return {'ADMIN_MEDIA_URL': settings. ADMIN_MEDIA_PREFIX} add your context processor to your settings. Py file: TEMPLATE_CONTEXT_PROCESSORS = ( "your_app.

Context_processors. Admin_media" ) Use RequestContext in your view to add your context processors in your template: from django. Template import Template, context, RequestContext from django.

Shortcuts import render_to_response def my_view(request): return render_to_response( "index. Html", context_instance=RequestContext(request) ) and finally, in your template: ... path to admin media ...

Nice example. One suggestion, the admin_media function should probably take 'request' as the argument not 'context' to make it clear that custom context processors need to accept a HttpRequest object. – mcqwerty Oct 21 '09 at 23:40 The down side of this approach is that you need to explicitly link the specific settings in settings.Py that you want to be available to the context renderer.

I could imagine a solution which would use the convention of uppercase attributes in settings. Py and auto-build the context. I'll add an example below as a separate response.

– IanSR Mar 28 at 13:13.

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.

2 I think this is the most elegant solution, as it works as dropin without changing code. – flying sheep Oct 5 at 7:51 @flyingsheep What do you mean "without changing code"? – Michael Mior Dec 11 at 5:57 that you can leave the rest of your application unaltered: you add one tag and use it, instead of having to add context processors (which means that you have to edit your application at several places) – flying sheep Dec 11 at 12:04.

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): _contextk = 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 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: contextself. 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}}.

I find the simplest approach being a single template tag: from django import template from django. Conf import settings register = template.Library() # settings value @register. Simple_tag def settings_value(name): try: return settings.

__getattr__(name) except AttributeError: return "" Usage: {% settings_value "LANGUAGE_CODE" %}.

Your solution is missing the import for register. I send an edit request. But basically it needs to have two more lines.

From django import template register = template.Library() – Jorge Vargas Oct 21 at 17:32 Duh! Good catch, thanks for editing. :) – Berislav Lopac Oct 23 at 8:55.

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): contextself. Cxtname = self. Variable return '' def get_from_setting(parser, token): as_value = variable = default = '' bits = token.contents.split() if len(bits) == 4 and bits2 == 'as': variable = bits1 as_value = bits3 elif len(bits) == 5 and bits3 == 'as': variable = bits1 default = bits2 as_value = bits4 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 cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions