I’m writing my first real project in Django and I have a problem with properly setting DEBUG
in development and production. In my settings.py
project file I have:
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', 'True') == 'True'
So I expect that it should work as follows. By default DEBUG
is set to True
(I use this in my development). But on my production server I have an environmental variable DJANGO_DEBUG
set to "False"
so Django should set DEBUG
to False
.
But this does not work! When I go to my_website/notexistingurl
I see Django detail error page which says that I have DEBUG
set to True
in my settings.py
file. And to make this completely unclear to me, when I open a python shell on my server it says that os.environ.get('DJANGO_DEBUG', 'True') == 'True'
is False
.
Does anyone have an idea what I am missing? Because to me it looks like two completely contradictory things!
Advertisement
Answer
This is more a guess, but normally the Django server will not run under the same user as the “administrator”. Indeed, as an extra security measure often such processes run under a separate user with limited privileges.
The aim is to prevent users that somehow can inject code in your Django application to gain more control. Indeed, imagine that a hacker found a way to evaluate arbitrary Python code by the Django server, then that hacker could eventually get control to all thinks the user that is running the Django app has control over such as files, devices, internet connections, etc. To limit this, often the Django app will run with a user that has that much privileges necessary to run the Django app, but not (much) more than that. While there might still be exploits to perform privilege escalation, this will at least make it more difficult and time-consuming.
This thus means that the environment of the user with which you are setting up the Django app, is not the user that runs the Django app, and therefore the environment variable probably is not set for that user. There is no universal way to solve this, since this likely depend on your hosting provider, but (very) likely there are ways to set environment variables for the django app user.
But nevertheless, it might be better to “reverse” the setting: right now you run in debug mode by default, and only in production when explicitly set. That is more risky, since things could get wrong when setting the environment variable, or deploying the application. When the Django app runs in debug mode it shows fragments of the source code, and one perhaps can manipulate the view that serves static/media files to serve more sensitive files. It might be better to run by default in production mode, and only run in debug mode when explicitly stated. For example with:
DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True'