The best way to store constants in Django

6.1k Views Asked by At

I have a Django application and use GitHub for CI. Now I run into the problem that I have a merge conflict with constants import every time I merge. Another developers are importing constants vary often, so do I. Directories tree looks like that:

main_app > 
...main_app 
...api 
...aws_lambda 
...billing 
...utils 
...and many other directories

Each sub-application has its own file constants.py. Constants import looks like that:

from utils.constants import const1, const2, const3, const4 
from billing.constants import const5, const6

How I need to rewrite those imports to decrease merge conflicts in future? Is there a better way than the one below?

import utils.constants as utils_const
import billing.constants as billing_const
...
var = utils_const.const1

What is the best practice to store constants in Django app?

3

There are 3 best solutions below

0
On BEST ANSWER

For constants that will only be used by one module, just define them in that module. For constants that are used by the whole project, the convention is to add them to your settings file. For constants used throughout a single app, I think your approach of having a constants.py per app is fine.

1
On

There is an issue on store constant in settings if some of the apps are shared in different django project.

In this case, add an constant application is recommend from the point of my view. Also you will get the benefit of django admin on configuring

0
On

You could also place them in the apps' __init__.py, one less file to read!

Then use as:

# Many constants:
import utils

print(utils.const2, utils.const3, utils.const4)


# Single constant (as the code base grows, this may become tiresome)
from billing import const1

print(const1)

You can also place them in apps.py since that file is loaded anyway as well, and semantically it's for configuring the app.