baltasvejas baltasvejas - 6 months ago 15
Python Question

List quickly all settings of your Django project

Probably this will not be difficult question for python experts, so please help. I want to quickly list all settings of my django project. I want to have a simple python script for that (in a separate file). Here is how I started:

from django.conf import settings

settings.configure()
settings_list = dir(settings)

for i in settings_list:
settings_name = i
print settings_name


In this way I get names of all settings. However after each
settings_name
I want to print its value. Tried many ways. Looks like those settings are actually empty. For example:

print settings.INSTALLED_APPS


returns empty list. I execute the script from django root directory and inside project's virtual environment.

Please suggest the right method to print out all settings for my Django project.

Answer

There are two problems which has to be answered: 1) settings are empty 2) how to iterate over attributes and values in settings object.

Regarding empty settings - referencing to django documenation

from django.conf import settings
settings.configure()
print settings.SECRET_KEY

should work, BUT for some reason it didn't in my case. So instead below code worked for me:

from django.conf import settings
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'my_django_project.settings'
print settings.SECRET_KEY

Then in order to collect attributes and values from settings object, I used below code, which I actually borrowed from django-print-settings:

a_dict = {}

for attr in dir(settings):
    value = getattr(settings, attr)
    a_dict[attr] = value

for key, value in a_dict.items():
            print('%s = %r' % (key, value))

To summarize, my full code in my print_settings.py file now looks:

from django.conf import settings
import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'my_django_project.settings'

a_dict = {}

for attr in dir(settings):
    value = getattr(settings, attr)
    a_dict[attr] = value

for key, value in a_dict.items():
            print('%s = %r' % (key, value))
Comments