Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Constants in Django

Tags:

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?

like image 797
Edan Maor Avatar asked Oct 28 '10 11:10

Edan Maor


1 Answers

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) 
like image 170
John Mee Avatar answered Oct 04 '22 14:10

John Mee