[Django]-Defining Constants in Django

19👍

Both Luper and Vladimir are correct imho but you’ll need both in order to complete your requirements.

  • Although, the constants don’t need to be in the settings.py, you could put them anywhere and import them from that place into your view/model/module code. I sometimes put them into the __init__.py if I don’t care to have them to be considered globally relevant.

  • a context processor like this will ensure that selected variables are globally in the template scope

    def settings(request):
        """
        Put selected settings variables into the default template context
        """
        from django.conf import settings
        return {
            'DOMAIN':     settings.DOMAIN,
            'GOOGLEMAPS_API_KEY': settings.GOOGLEMAPS_API_KEY,
        }
    

But this might be overkill if you’re new to django; perhaps you’re just asking how to put variables into the template scope…?

from django.conf import settings

...
# do stuff with settings.MIN_TIME_TEST as you wish

render_to_response("the_template.html", { 
    "MIN_TIME_TEST": settings.MIN_TIME_TEST 
}, context_instance=RequestContext(request)

6👍

To build on other people’s answers, here’s a simple way you’d implement this:

In your settings file:

GLOBAL_SETTINGS = {
    'MIN_TIME_TEST': 'blah',
    'RANDOM_GLOBAL_VAR': 'blah',
}

Then, building off of John Mee’s context processor:

def settings(request):
    """
    Put selected settings variables into the default template context
    """
    from django.conf import settings
    return settings.GLOBAL_SETTINGS

This will resolve the DRY issue.

Or, if you only plan to use the global settings occasionally and want to call them from within the view:

def view_func(request):
    from django.conf import settings
    # function code here
    ctx = {} #context variables here
    ctx.update(settings.GLOBAL_SETTINGS)
    # whatever output you want here

3👍

Consider putting it into settings.py of your application. Of course, in order to use it in template you will need to make it available to template as any other usual variable.

2👍

Use context processors to have your constants available in all templates (settings.py is a nice place to define them as Vladimir said).

2👍

Context processors are better suited at handling more dynamic object data–they’re defined as a mapping in the documentation and in many of the posts here they’re being modified or passed around to views–it doesn’t make sense that a template may lose access to global information because, for example, your forgot to use a specialized context processor in the view. The data is global by definition & that couples the view to the template.

A better way is to define a custom template tag. This way:

  • templates aren’t relying on views to have global information passed into them
  • it’s DRY-er: the app defining the global settings can be exported to many projects, eliminating common code across projects
  • templates decide whether they have access to the global information, not the view functions

In the example below I deal with your problem–loading in this MIN_TIME_TEST variable–and a problem I commonly face, loading in URLs that change when my environment changes.

I have 4 environments–2 dev and 2 production:

  • Dev: django-web server, url: localhost:8000
  • Dev: apache web server: url: sandbox.com -> resolves to 127.0.0.1
  • Prod sandbox server, url: sandbox.domain.com
  • Prod server: url: domain.com

I do this on all my projects & keep all the urls in a file, global_settings.py so it’s accessible from code. I define a custom template tag {% site_url %} that can be (optionally) loaded into any template

I create an app called global_settings, and make sure it’s included in my settings.INSTALLED_APPS tuple.

Django compiles templated text into nodes with a render() method that tells how the data should be displayed–I created an object that renders data by returnning values in my global_settings.py based on the name passed in.

It looks like this:

from django import template
import global_settings

class GlobalSettingNode(template.Node):
    def __init__(self, settingname):
        self.settingname = settingname;
    def render(self, context):
        if hasattr(global_settings, self.settingname):
            return getattr(global_settings, self.settingname)
        else:
            raise template.TemplateSyntaxError('%s tag does not exist' % self.settingname)

Now, in global_settings.py I register a couple tags: site_url for my example and min_test_time for your example. This way, when {% min_time_test %} is invoked from a template, it’ll call get_min_time_test which resolves to load in the value=5. In my example, {% site_url %} will do a name-based lookup so that I can keep all 4 URLs defined at once and choose which environment I’m using. This is more flexible for me than just using Django’s built in settings.Debug=True/False flag.

from django import template
from templatenodes import GlobalSettingNode
register = template.Library()


MIN_TIME_TEST = 5

DEV_DJANGO_SITE_URL = 'http://localhost:8000/'
DEV_APACHE_SITE_URL = 'http://sandbox.com/'
PROD_SANDBOX_URL = 'http://sandbox.domain.com/'
PROD_URL = 'http://domain.com/'

CURRENT_ENVIRONMENT = 'DEV_DJANGO_SITE_URL'



def get_site_url(parser, token):
    return GlobalSettingNode(CURRENT_ENVIRONMENT)

def get_min_time_test(parser, token):
    return GlobalSettingNode('MIN_TIME_TEST')

register.tag('site_url', get_site_url)
register.tag('min_time_test', get_min_time_test)

Note that for this to work, django is expecting global_settings.py to be located in a python packaged called templatetags under your Django app. My Django app here is called global_settings, so my directory structure looks like:

/project-name/global_settings/templatetags/global_settings.py
etc.

Finally the template chooses whether to load in global settings or not, which is beneficial for performance. Add this line to your template to expose all the tags registered in global_settings.py:

{% load global_settings %}

Now, other projects that need MIN_TIME_TEST or these environments exposed can simply install this app =)

0👍

In the context processor you can use something like:

import settings

context = {}
for item in dir(settings):
    #use some way to exclude __doc__, __name__, etc..
    if item[0:2] != '__':
        context[item] = getattr(settings, item)

0👍

Variant on John Mee’s last part, with a little elaboration on the same idea Jordan Reiter discusses.

Suppose you have something in your settings akin to what Jordan suggested — in other words, something like:

GLOBAL_SETTINGS = {
   'SOME_CONST': 'thingy',
   'SOME_OTHER_CONST': 'other_thingy',
}

Suppose further you already have a dictionary with some of the variables you’d like to pass your template, perhaps passed as arguments to your view. Let’s call it my_dict. Suppose you want the values in my_dict to override those in the settings.GLOBAL_SETTINGS dictionary.

You might do something in your view like:

def my_view(request, *args, **kwargs)
    from django.conf import settings
    my_dict = some_kind_of_arg_parsing(*args,**kwargs)
    tmp = settings.GLOBAL_SETTINGS.copy()
    tmp.update(my_dict)
    my_dict = tmp
    render_to_response('the_template.html', my_dict, context_instance=RequestContext(request))

This lets you have the settings determined globally, available to your templates, and doesn’t require you to manually type out each of them.

If you don’t have any additional variables to pass the template, nor any need to override, you can just do:

render_to_response('the_template.html', settings.GLOBAL_SETTINGS, context_instance=RequestContext(request))

The main difference between what I’m discussing here & what Jordan has, is that for his, settings.GLOBAL_SETTINGS overrides anything it may have in common w/ your context dictionary, and with mine, my context dictionary overrides settings.GLOBAL_SETTINGS. YMMV.

Leave a comment