Django — Setting DJANGO_SETTINGS_MODULE / Environment Variables from Python

You know, I learned this and completely forgot after months of not dealing with it. Google searches are so difficult to reach the right subject.

I’m certain this will be something I refer to in the future..

Setting environment variables via Python is as simple as:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

Of course, this doesn’t permanently set the variable, but if you have a script that needs that envvar, perfect.

Enjoy.

7 thoughts on “Django — Setting DJANGO_SETTINGS_MODULE / Environment Variables from Python

      1. Haha yeah, perhaps 🙂 Or maybe it’s just very useful! (At least for beginners in Python like myself..)

  1. Hehe, I’m glad. I started writing this stuff down because I noticed I’d forget some problems and research the same problem over and over

  2. Thanks for this — not sure you will respond as this note is 6 years after this post. My question: where do you put the import os… script? What file? Where? Thanks!

    1. Hey Tony, put it wherever it’s most useful to you. Often times that’s somewhere like wsgi.py which is called before any of the django machinery is invoked.. thereby setting the envvar across the whole project.

      But really it depends on your use case. Most people I think would be using this to manually set `DJANGO_SETTINGS_MODULE` wherever needed. Say a one off script importing your django models and doing a periodic task.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s