jazzband/django-constance

How do I set settings keys for other libraries I’m using in my project?

ericswpark opened this issue · 4 comments

Describe the problem

I’m trying to add django-constance to my project. One of my dependencies has a configuration key that I’d like to configure within Constance. Unfortunately, I cannot import Constance within config/settings.py as it will cause all the tests to fail (and also I’m not sure if this is allowed — if my understanding is correct settings.py sets up all the Django apps and what not and calling Constance before Django has set up all apps could cause undefined behavior?)

So given a standard Django configuration key defined in config/settings.py, how do I set that key using Constance?

NoPH8 commented

Maybe you just need to setup configuration key in settings.py and use this value as default for constance field? After that you can use in your app constance-value.

# settings.py
...
DEFAULT_ANSWER = 42

CONSTANCE_CONFIG = {
    'THE_ANSWER': (DEFAULT_ANSWER, 'Answer to the Ultimate Question of Life, The Universe, and Everything'),
}
...
# your_app/tools.py
from constance import config
...
def foo():
    return config.THE_ANSWER
...

The function foo() will return 42 until you do not change 'THE_ANSWER'-value from the admin panel, or management command etc.

Right, but the problem is the app is a library that I cannot modify, that calls configuration values from django.conf.

I could technically fork the library and make the changes, but this becomes infeasible over time as I add more dependencies, increasing the number of config values I need to adjust.

Let me show an example of what I’m trying to do. The given library will get the configuration value like this:

from django.conf import settings

some_config = settings.LIBRARY_CONFIG_A

Since I cannot change this snippet of code (without forking), I need to set the configuration key LIBRARY_CONFIG_A in config/settings.py, like this:

from constance import config   # problem here

# …snip…

LIBRARY_CONFIG_A = config.CUST_LIBRARY_CONFIG_A

Unfortunately, I cannot import constance within the settings.py file as it is where it initializes all the Django apps and dependencies. Doing so anyway will cause Constance to spit out an error complaining that it’s not yet initialized.

NoPH8 commented

In that case you can take a look on signals section in the constance docs.
But I think it's not a good idea because of django warns about altering settings in runtime. And this can cause various errors especially when runs multiple instance of django app.

Thanks @NoPH8. After reading some more posts and the documentation it seems like there is currently no way to achieve this without modifying said library or just forcing the user to set up the settings before starting the server.