Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server Error (500) on Django when template debug is set to False?

I am seeing Django 500 Error when I set DEBUG = False in Django. I am using Django 1.5 and Python 2.7. I have also included ALLOWED_HOSTS in my template. Here's my full settings.py:

# Django settings for genalytics project.
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
import djcelery
import os
__file__ = os.getcwd()

ROOT_PATH = os.path.dirname(__file__)

djcelery.setup_loader()

#New in Django 1.5
ALLOWED_HOSTS = ['localhost', '127.0.0.1:8000'] 

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
     ('sachit', '[email protected]')
)


BROKER_TRANSPORT = "sqlalchemy"
BROKER_URL = "sqla+mysql://root:password@localhost/galaxy"


MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'galaxy',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': ''                      # Set to empty string for default. Not used with sqlite3.
      }              
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''

STATIC_URL = '/static/'

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"

AUTHENTICATION_BACKENDS = (
    'fileupload.backend.AuthBackend',
 )

# Additional locations of static files
STATICFILES_DIRS = (
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '$ec_7m$05ddhhc_cy(j-i^%70ochjmx*$0_o!$u1q9rkkd(ai$'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS += (
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages'
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'fileupload.middleware.AutoLogout'
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

#Pagination Setting
ENDLESS_PAGINATION_PREVIOUS_LABEL = '<'
ENDLESS_PAGINATION_NEXT_LABEL = '>'

ENDLESS_PAGINATION_FIRST_LABEL = '|<'
ENDLESS_PAGINATION_LAST_LABEL = '>|'

ROOT_URLCONF = 'genalytics.urls'

SESSION_COOKIE_AGE = 30 * 60


# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'genalytics.wsgi.application'

TEMPLATE_DIRS = (
            os.path.join(ROOT_PATH, 'fileupload/templates'),


)

DESTINATION = '/home/zurelsoft/files/'

AUTO_LOGOUT_DELAY = 30

AUTH_USER_MODEL = 'fileupload.user'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'fileupload',
    'django.contrib.admin',
    'endless_pagination',
    'djcelery',
    'endless_pagination'
)



# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },

    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

What's wrong?

Updated the logging as Ryu_hayabusa suggested and I am getting this error in the console:

Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x22e08d0>>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 114, in inner_run
    ipv6=self.use_ipv6, threading=threading)
  File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 193, in run
    httpd.serve_forever()
  File "/usr/lib/python2.7/SocketServer.py", line 235, in serve_forever
    r, w, e = _eintr_retry(select.select, [self], [], [],
AttributeError: 'NoneType' object has no attribute 'select'
like image 300
pynovice Avatar asked Jun 07 '13 10:06

pynovice


People also ask

What is server error 500 in Django?

When DEBUG is False , Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater). This gives the administrators immediate notification of any errors.

How do I change DEBUG to false?

Open your settings.py file (or settings_local.py ) and set DEBUG = False (just add that line if necessary).

How does Django fix internal server error?

As first step, enable DEBUG mode in Django settings module to see if that fixes the issue or at least causes a description of the error in the browser. It is quite common to get a 500 error response delivered back from Django with no record of the exception being logged.


2 Answers

Use the following LOGGING settings, then you should be able to see the error in the console.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },

    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console':{
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

remember to set DEBUG = False

like image 22
Ryu_hayabusa Avatar answered Sep 30 '22 19:09

Ryu_hayabusa


I got the 500 Internal Server error after switching DEBUG off as well. Another reason this could happen is if you have an extra / at the start of the relative static path. So replace:

<link rel="stylesheet" href="{% static '/css/somecustom.css' %}">

with

<link rel="stylesheet" href="{% static 'css/somecustom.css' %}">

i.e. search and replace {% static '/ with {% static ' in your template files.

To understand this further you can read up on the caching behaviour of Django’s ManifestStaticFilesStorage backend.

like image 88
Nitin Nain Avatar answered Sep 30 '22 17:09

Nitin Nain