Search code examples
pythondjangopython-3.xdjango-settings

How do I turn django's settings object into a dict?


What I have:

from django.conf import settings

def settings_to_dict(settings)
    cfg = {
        'BOTO3_ACCESS_KEY': settings.BOTO3_ACCESS_KEY,
        'BOTO3_SECRET_KEY': settings.BOTO3_SECRET_KEY,
        # repeat ad nauseum
    }
    return cfg

instance = SomeClassInstantiatedWithADict(**settings_to_dict(settings))

What I'd like (using Django 1.11):

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.to_dict())

I've tried:

from django.conf import settings

instance = SomeClassInstantiatedWithADict(**settings.__dict__)

which is close, but __dict__ only gets a small subset of the settings, which I assume are hard coded ones as opposed to added attributes. Thanks for any help!


Solution

  • Use the following code:

    from django.conf import settings
    instance = settings.__dict__['_wrapped'].__dict__
    

    Then you will have the whole settings dict in instance as dictionary.