Reputation: 1778
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.
Upvotes: 2
Views: 2351
Reputation: 1693
You can call Django's built-in diffsettings:
from django.core.management.commands import diffsettings
output = diffsettings.Command().handle(default=None, output="hash", all=False)
desensitized = []
for line in output.splitlines():
if "SECRET" in line or "KEY" in line:
continue
desensitized.append(line)
print("\n".join(desensitized))
Upvotes: 3
Reputation: 8550
import django, os
from django.conf import settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' # Settings will pick this up on lazy init.
for attr in dir(settings):
print "%-40s: %s" % (attr, getattr(settings, attr))
Upvotes: 0
Reputation: 1778
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))
Upvotes: 2
Reputation: 1778
This is not the answer I am expecting, but I found another good solution how to print all settings of Django project.
This can be done by installing python package django-print-settings:
pip install django-print-settings
I found it from here https://readthedocs.org/projects/django-print-settings/. Please refer to that site for setup and usage.
Upvotes: 0