Django: Override Debug=True from manage.py runserver command
Is there an easy way to tell Django's runserver
to override a single variable in the settings.py
file?
I would love to be able to call:
python manage.py runserver 0.0.0.0:8000 Debug=False
Any thoughts?
Motive: have a particular site where there are hundreds of dat开发者_运维问答abase queries to show or save a particular page, I'd like to be able to turn off debug quickly without having to edit my settings file (which has the possibility of being forgotten).
I think you have two options
The simplest is probably a custom settings override, something like:
# no_debug_settings.py
# pull in the normal settings
from settings import *
# no debug for us
DEBUG = False
Now, when you want to start without debugging, you'd run:
python manage.py runserver --settings=no_debug_settings 0.0.0.0:8000
As an alternative, you could just customise your manage.py
file. That imports settings, and passes it to the execute_manager
. If you added some code between the import and the call, you could have it check for extra arguments and alter the settings as needed. It's a bit more fiddly and prone to break / be forgotten, so I'd suggest the override settings wrapper is probably your best way to go.
I edited my settings.py
file with a conditional block, like this:
import os # If needed.
if os.environ.get('DJANGO_DEBUG'):
print("Debug is enabled.")
DEBUG = True
# When not specified, ALLOW_HOSTS defaults to:
# ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]']
else:
DEBUG = False
ALLOWED_HOSTS = ["*"]
Then, run your server by passing the environmental variable DJANGO_DEBUG=1
. You can name the variable anything you want so long as you are consistent:
DJANGO_DEBUG=1 python -Wall manage.py runserver
Omit that environmental variable when calling manage.py
to disable debug (because setting it to any value, including 0
will still make it true to the Python code.)
Update: A commenter stated that the ALLOWED_HOSTS
directive is ignored when DEBUG
is True
. This is only true in older versions of Django. The current behavior is to honor ALLOWED_HOSTS
or default to localhost addresses if it isn't specified when DEBUG
is enabled. My answer is updated to reflect this as a minor correction.
This is sourced from the Django documentation:
When DEBUG is True and ALLOWED_HOSTS is empty, the host is validated against ['localhost', '127.0.0.1', '[::1]']
Additionally, it states that the behavior your comment on is now outdated in a few major version lines:
In older versions, ALLOWED_HOSTS wasn’t checked if DEBUG=True. This was also changed in Django 1.10.3, 1.9.11, and 1.8.16 to prevent a DNS rebinding attack.
精彩评论