Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Global settings variables

Tags:

django

Suppose I have some global settings for my Django project, stored in a text file for easy editing. I want to load the settings, and then store these variables such that they are accessible from any of my view functions. However, I have read that global variables in Django are discouraged. So, how should I do it? I know how to store these variables in a database, but this seems overkill just for storing a few simple variables.

like image 359
Karnivaurus Avatar asked Mar 05 '14 16:03

Karnivaurus


People also ask

Can I use global variable in Django?

Local and Global Variables Global Variables are declared outside any function, and they can be accessed anywhere in the program whereas Local Variables are maintained and used only inside a function any other function can't access them. Keep in mind there can be Local variables of the same name in different functions.

What is Django conf settings?

django. conf. settings abstracts the concepts of default settings and site-specific settings; it presents a single interface. It also decouples the code that uses settings from the location of your settings.

What is the use of settings py in Django?

settings.py is a core file in Django projects. It holds all the configuration values that your web app needs to work; database settings, logging configuration, where to find static files, API keys if you work with external APIs, and a bunch of other stuff.


2 Answers

As alecxe has already pointed out, you can use the settings system. This is the customary way to set values that must be used project-wide. If you read the documentation I've linked too you'll see that they cover very early on that page how to set your own settings.

One thing you must not do when you use Django's settings system is refer to settings at the top level of your modules. For instance if you have a view that does this:

from django.conf import settings

FOO = settings.FOO

(Or alecxe's print statement.) This will prevent values from being overriden. The documentation here goes over the details. I recall having had problems in testing due to this because some of my tests were trying to override the default values, and failed.

The settings system I've mentioned above should be used for values that are meant to be set at start up and not changed afterwards. If you want to record settings that can be changed by the site's administrator at run time, you should use a database of some sort.

like image 195
Louis Avatar answered Oct 05 '22 23:10

Louis


Just store your variables in settings.py, this is the best and preferrable way to store your project-specific settings. Then, you can always access them by importing django.conf.settings:

from django.conf import settings

print settings.MY_SETTING

Hope that helps.

like image 20
alecxe Avatar answered Oct 05 '22 23:10

alecxe