Defining Constants in Django Defining Constants in Django python python

Defining Constants in Django


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 wishrender_to_response("the_template.html", {     "MIN_TIME_TEST": settings.MIN_TIME_TEST }, context_instance=RequestContext(request)


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


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.