The best way to store constants in Django
Asked Answered
V

3

7

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?

Vigilant answered 11/1, 2018 at 11:43 Comment(0)
P
21

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.

Pietra answered 11/1, 2018 at 12:17 Comment(0)
W
0

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.

Worldweary answered 30/1, 2022 at 19:8 Comment(0)
S
-2

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

Salvo answered 4/6, 2020 at 12:38 Comment(1)
This will make all apps tightly coupled to each other, you want to have pluggable apps.Worldweary

© 2022 - 2024 — McMap. All rights reserved.