Heroku Django DEBUG Setting not applied - django

I currently have a running production Django application on Heroku. Unfortunately, I haven't been able to turn off the DEBUG setting on Heroku. Turning it off locally works fine, but when pushed to Heroku (after heroku config:set DEBUG=False), it doesn't apply.
The error pages are still the default DEBUG ones instead of the 404, 403, and 500 templates in our template root.
I have also tried using a DJANGO_DEBUG setting in case there were any environment conflicts with DEBUG, and casting the result to a boolean in the settings file. heroku config shows the settings in the environment are correct. This is on Django 1.3, Heroku Cedar.
Any tips or solutions?

Does your django settings.py file even look in the environment?
It does not, by default, care about anything you've set in the environment (via "config:set"). If you're "casting" the environment to a boolean, make sure you're casting it correctly. bool('False') is still True.
It's simplest just to detect if the environment variable exists so you don't have to worry about type casting or specific formats of the configuration.
DEBUG = os.environ.get('DEBUG', False)
To disable debug, remove the variable from the environment instead of trying to type cast... it just seems much more reliable and fool proof. config:unset DEBUG

The problem is that the environment variable is not a boolean, rather a string.
So do place below line in settings.py
DEBUG = (os.environ.get('DEBUG_VALUE') == 'True')

Related

Internal server error running Django on Heroku accessing from browser

I think this is a simple fix, but I've deployed quite a few Django apps to Heroku and I still can't figure out what's going on.
Accessing https://dundjeon-finder.herokuapp.com/ gives me a 500 error when using the browser/curl, but if I shell into the app using heroku run ./manage.py shell I can render the views no problem. My logs aren't telling me anything (just that the response is 500) despite DEBUG being set to True, and Sentry isn't receiving an error (it has previously when the database env variable was set badly), so I'm assuming it's something to do with the way the request works.
The repo is public, any help would be much appreciated! The settings file is here.
Well it was because of using asgi instead of wsgi. I'm not sure why that caused the errors, but will do some more searching.

django DEBUG=False still runs in debug mode

I'm having issues setting my DEBUG = False on my deployed server (on heroku).
I don't believe I've seen this before, but setting debug to false is not getting rid of debug mode for my project. This means that when there are 500 errors it shows the error, and 404 errors are showing all my urls.
What's strange is that when i log into the server and run get the setting value from django.conf import settings settings.DEBUG it shows as False, which is what I set it to for the production server. TEMPLATE_DEBUG is also set to False.
I don't know I've ever seen this before where DEBUG = False but it's still acting in debug mode. Any ideas?
EDIT:
Thought I'd put this little note too because it's very common for people to be getting 500 or 400 errors when switching debug to False. I am not getting any errors, my project is just acting like it's in DEBUG mode.
# settings/dev.py
from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
if not DEBUG:
ALLOWED_HOSTS = ['localhost']
SECRET_KEY = 'localsecret1234123412341234'
# settings/prod.py
from .base import *
import dj_database_url, os
DEBUG = os.environ.get("DEBUG", False)
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['mydomain.com']
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
The root cause of issue - False translated to 'False' string not bool.
Used next solution (settings.py):
DEBUG = os.getenv('DEBUG', False) == 'True'
i.e.: in this case DEBUG will set to (bool) True, only if the environment variable is explicitly set to True or 'True'.
Good luck configuring! :)
As a note for others: I had the same problem; I configured my production website on a VM with gunicorn and nginx, following the tutorial for ubuntu 16.04 from the digital ocean documentation.
I wasn't able to turn off the debug mode, even when restarting the nginx systemd's service: the solution was to restart also the gunicorn service:
# systemctl restart nginx gunicorn
If somebody is using python-decouple for env variables and having trouble with DEBUG you have to use this line to retrieve booleans:
from decouple import config
DEBUG = config('DEBUG', default=False, cast=bool)
I'll put this as an actual answer for people that come after.
There are three main areas that this can happen, where 'this' is basically:
I've changed something in my settings, but it doesn't seem to be reflected in the operation of my app!
Server hasn't been reset after code changes made.
Local and Dev settings haven't overridden/or are overriding in unexpected ways
A local Environment Variable is overriding the attempt at hardcoding it
On Heroku, as in this example, Environment Variables are set this way. A more general guide to using them in Linux enviroments is available here.
Using an example from the question, you can see the environment variables being used in:
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
This uses the os library to go out to the system, and check for an environment variable called DJANGO_SECRET_KEY.
A better example is the:
DEBUG = os.environ.get("DEBUG", False)
This is good because it tries to get it from the environment, and if that fails, uses the second value in the tuple as the default: in this case, False.
During the course of debugging, you can hunt down your settings using printenv from the linux shell, which will print out all of the available EnvVars. If they're not there, you can set them in the format:
export DJANGO_SETTINGS_MODULE=mysite.settings
In this instance, it's probably better to unset the environment variable, rather than typecasting, as per this related answer.
This ended up being an issue with the config variable being "False" instead of False, and so debug wasn't properly set to the boolean value. Shoutout to #WithNail for helping get to the answer
DEBUG takes Boolean value.
The os.environ.get("DEBUG", False) returns string value.
All the string value while typecasting return True.
That's why the DEBUG is True.
print(bool(os.environ.get("DEBUG", False))) # output: True
print(bool("False")) # output: True
print(bool("")) # output: False
To solve issue in heroku don't set any value to config var. it will return null string and after typecasting it will return False:
When you use the module decouple (pip install python-decouple) make sure you cast DEBUG to a bool. Thus settings.py should have the following line:
from decouple import config
DEBUG = config('DEBUG', default=False, cast=bool)
where in the .env file
DEBUG = False # or True
I also experienced this problem as I was loading the debug setting from an environment variable DEBUG = os.environ.get('DEBUG_MODE')).
This set the DEBUG value as a string, not a boolean.
To fix this, I hardcoded DEBUG = False in my prod settings file.
I got the same error that OTREE_PRODUCTION=1 gives error 500 on Heroku. What I did is to make a new app (Note to change Heroku stack to make it compatible with your Python version) , upload codes to this new app, and set OTREE_PRODUCTION=1 for this new app.
I had the same issue & none of the solutions worked. My error stems from the the server configuration. I have multiple apps served by NGINX & GUNICORN. One of the apps is linked with the default server.
This means that any request not matching any of the IP:port listening pair server blocks is served by the default server. While debugging I happened to have set the settings.py of the app linked with the default server block to DEBUG=True & forgot to set it back to DEBUG=False.
So bringing settings.py of the default app's server block back to DEBUG=False, solved the issue.

how to set production environment variables in django

I am having some trouble setting environment variables in my production environment, I have some logic in django settings that depends on it. I have tried exportng it through variouse places '/etc/profile, ~.bashrc, etc'
The problem is that those only set them when there is a login (I believe?) But if I navigate a browser to the server I can see that the variable was not set correctly through the debug. I am running django1.7/gunicorn/nginx. I suspected to put it in the gunicorn /etc/init/gunicorn.conf but that did not work.
How can I set this?
You could set them in the WSGI file. – Simeon Visser
Thanks, this solved my problem for my purposes. I don't believe that the wsgi file runs on the dev server so it worked perfectly and only set the variable on the production. Thanks

Pycharm error: Improperly configured

After having an unexpected shutdown on my DEV machine, when going back to Pycharm project, I noticed the Django view file I was editing (which had 700+ lines) when that happened, it was completely empty. I managed to restore it from a backup; no loss there.
The problem comes up when trying to debug, it returns this error: "ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Process finished with exit code 137
The Pycharm settings Django Support (project root, settings & manage script) have the expected values as well.
If I run the project with the ./manage .py runserver command, everything is fine. I can even access the DB with manage.py dbshell. I looked at my settings file and everything seems OK. I also updated from version 3.0.1 to 3.1.1, and no difference.
I'm using Django 1.6.1 and postgresql 9.2.7. What can I do?
For Pycharm, just go to Run -> Edit Configurations, select your project on the right of the window from Debug Configuration, and you will see Environment variables on the right. Make sure you have set DJANGO_SETTINGS_MODULE=mysite.settings, if not just add one, it is as easy as fill a key value pair from the pop up dialog.
I'm using PyCharm Professional and the answers provided here didn't work for me.
I went to Build, Execution, Deployment -> Consule -> Django Console and then added DJANGO_SETTINGS_MODULE=my_app_name.settings to Environment Variables.

Issue with Heroku, configuration variables and django using S3

I'm having a very strange issue.
I have my django project running in Heroku using S3 to store my static assets.
I wanted to use the Heroku enviroment variables by setting them as follows:
heroku config:add AWS_S3_TOKEN=my_s3_token
heroku config:add AWS_S3_SECRET=my_s3_secret
And using them with python's os module:
import os
token = os.getenv('AWS_S3_TOKEN')
secret = os.getenv('AWS_S3_SECRET')
But heroku keeps throwing me the following error:
NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials
So, I ended up writing those parameters in my settings.py file and it works fine
Why is this happening?
If I run
heroku config
I can see all my seted variables and if i do
heroku run python manage.py shell
and then
import os
print os.getenv('AWS_S3_TOKEN')
For example, it prints the variable's value.
any clue on this???
Thank you in advance
I'm not familiar with python or Django, but I'm curious.
If you try your authentication with blank strings, do you get the same error?
If so, then I suspect it's about when you're doing this authentication dance. When are you doing it? At compile time, or at runtime? (If at compile time, look at this)
The app's environment variables aren't usually available while Heroku is compiling the slug and setting up the application, they're only available once the app is running. For a Django app, Heroku will run collectstatic as part of slug compilation, which is probably why you're seeing this error.
You can make the environment variables available during compilation by enabling a Heroku Labs feature:
heroku labs:enable user-env-compile
There's more information in this Heroku dev centre article: https://devcenter.heroku.com/articles/labs-user-env-compile