I have sensitive data (database passwords) in settings.py and I was advised to upload my Django project to a github repository before pushing it to Heroku on their "Getting Started with Django on Heroku". If I put settings.py in .gitignore, then presumably it won't get deployed with my project. How can I prevent settings.py from being exposed but still get it deployed with my project ?

- 1,048,767
- 296
- 4,058
- 3,343

- 538
- 6
- 19
-
You could use different branches, see http://stackoverflow.com/questions/10475273/git-have-different-gitignore-file-for-each-remote. – bennofs Sep 28 '13 at 21:53
-
Thanks, I thought of that but it sounded tedious. I think I figured out the best way to do it, which is to use Heroku's environment variables as in https://devcenter.heroku.com/articles/s3 and then use os.config["variableName"] to retrieve the value in settings.py . Pretty surprised this is not a more google-able problem though ... maybe this will help – J. Barca Sep 28 '13 at 22:16
-
You don't need to push to github, just to git. It could even be a local git repository without any remote. In the "getting started" they just suggest to install system-wide the github .gitignore. – esauro Sep 28 '13 at 22:22
2 Answers
You can use environment variables (with heroku config:add SECRET=my-secret
) to setup sensitive data and retrieve them in your settings with:
SECRET = os.environ.get('SECRET', 'my-default-secret-key')
If you don't want to be able to start your app without having set up some data, use this syntax instead:
SECRET = os.environ['SECRET']
It will raise an exception if you didn't set the SECRET
environment variable.

- 586
- 3
- 13
-
However, I can't find the syntax os.env anywhere, I believe it is: os.environ["HOME"] – J. Barca Sep 29 '13 at 15:45
You should use a tool designed for factoring out sensitive data. I use YamJam https://pypi.python.org/pypi/yamjam/ . It allows all the advantages of the os.environ method but is simpler -- you still have to set those environ variables, you'll need to put them in a script/ rc file somewhere. YamJam eliminates these questions and stores these config settings in a config store outside of the project. This allows you to have different settings for dev, staging and production.
from YamJam import yamjam
secret = yamjam()['myproject']['secret']
Is the basic usage. And like the os.environ method, it is not framework specific, you can use it with Django or any other app/framework. I've tried them all, multiple settings.py files, brittle logic of if/then and environment wrangling. In the end, I switched to yamjam and haven't regretted it.

- 1,229
- 1
- 10
- 5
-
This approach is much easier than creating environment variables and makes things a bit more organized, thanks for the answer! – Gabriel Belini Oct 15 '17 at 22:42