1

I want to sys.exit() the server when no settings module is defined.

As far as I'm aware a Django settings module can be passed in two ways:

  1. By running the server using --settings=app.settings.foo
  2. By setting an environment variable DJANGO_SETTINGS_MODULE=app.settings.foo.

How can I detect in my app when no settings module is defined, and where would be a good place to put this?

Blaise
  • 13,139
  • 9
  • 69
  • 97
  • You mean when certain settings for your app aren't defined? – Burhan Khalid Apr 17 '14 at 11:56
  • No, I mean when no settings *module* is defined when running the server, either via the settings parameter or the environment variable. — I could set some setting in my base settings file (which is imported by all other settings files), and in my app check if that setting exists, else: exit(), but that's a workaround that I want to use as a last resort. – Blaise Apr 17 '14 at 13:15

2 Answers2

1

You can try this in your init.py

import os.path

#Check if file exists every time you use runserver
if not os.path.isfile(/path/of/your/settings.py):
    sys.exit()

But if you want avoid this approach you can check if a enviroment variable exists. Also, if you want to raise an error when --settings it's not passed, you must override the parameter.

Community
  • 1
  • 1
Adrian Lopez
  • 2,601
  • 5
  • 31
  • 48
  • 1
    Actually you [can](http://programming.oreilly.com/2014/04/simplifying-django.html). – Burhan Khalid Apr 17 '14 at 11:55
  • Thank you for your answer. I don't want to check if the settings file exists, I want to know if a non-default settings file was used. I found a simple way, see my answer. – Blaise Apr 18 '14 at 09:03
1

In manage.py and project/wsgi.py:

Replace

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

With

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.exit")

Then create project/exit.py with contents:

import sys

print "No settings module specified."
sys.exit()

When you start the server without specifying --settings and without a DJANGO_SETTINGS_MODULE environment variable, it will print the message and exit.

Blaise
  • 13,139
  • 9
  • 69
  • 97