Alex Rivera | Logout

Defining Constants in Django

Asked 2010-10-28T11:27:06.540
27

I want to have some constants in a Django Projects. For example, let's say a constant called MIN_TIME_TEST.

I would like to be able to access this constant in two places: from within my Python code, and from within any Templates.

What's the best way to go about doing this?

EDIT: To clarify, I know about Template Context Processors and about just putting things in settings.py or some other file and just importing.

My question is, how do I combine the two approaches without violating the "Don't Repeat Yourself" rule? Based on the answers so far, here's my approach:

I'd like to create a file called global_constants.py, which will have a list of constants (things like MIN_TIME_TEST = 5). I can import this file into any module to get the constants.

But now, I want to create the context processor which returns all of these constants. How can I go about doing this automatically, without having to list them again in a dictionary, like in John Mee's answer?

Edit
Report

1 Answer

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.

answered 2010-10-28T20:50:40.283

Your Answer