Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Check if settings variable is set

Here is an example of what I'm trying to achieve. The desired effect is that a particular feature should take effect if and only if its relevant setting exists is defined. Otherwise, the feature should be disabled.

settings.py:

SOME_VARIABLE = 'some-string'
ANOTHER_VARIABLE = 'another-string'

random_code_file.py:

from django.conf import settings

if settings.is_defined('ANOTHER_VARIABLE'): # <- I need this.
    do_something(settings.ANOTHER_VARIABLE)
else:
    do_something_completely_different()

In the code above, I'm missing whatever I should do instead of settings.is_defined.

If this is the wrong approach to the problem altogether, I'd be happy to hear about alternative approaches as well. The desired effect is an auto-activated feature which only takes effect if the relevant setting exists. I would prefer avoiding some special settings.ACTIVE_FEATURES setting or a special value such as a blank string or None for the feature to assess whether it is to take effect or not.

The last thing I'd like to do is to use try/except. I'd rather go for an empty value indicating exclusion of the feature. - But if try/except-ing it is really the preferred method, I will mark the answer as correct if exhaustive sources or explanations are provided. In fact that goes for any answer.

So in short, I need the proper way to check if a settings variable is defined in Django.

Thanks in advance!

like image 208
Teekin Avatar asked Jul 24 '14 00:07

Teekin


Video Answer


1 Answers

It seemed you've made it the correct way: import setting object and check.

And you can try to use:

if hasattr(settings, 'ANOTHER_VARIABLE'):

instead of:

if settings.is_defined('ANOTHER_VARIABLE'):

I found the documentation, hope this might help.

like image 168
Alfred Huang Avatar answered Oct 20 '22 19:10

Alfred Huang