Kyle
Kyle

Reputation: 113

Django Heroku Debug = False, Static files cause Internal Server Error

RESOLVED: I'm not sure what combination of things I did to ultimately fix it, but the final piece was fixing my static file hierarchy. Before, I simply had /<base>/static/main.css but I changed this to /<base>/static/<project-name>/main.css and that somehow fixed the issue.

Original problem: I am currently trying to deploy a django app with Heroku. When I try to deploy with Debug=False however, I get an Internal Server Error, because the server cannot find the main.css style sheet. Note that when Debug=True everything works fine.

When I try python manage.py findstatic --verbosity 2 main.css in the commandline, I get the error message "No matching file found for 'main.css'. Looking in the following locations: /Users/Kyle/.local/share/virtualenvs/hostable-Ij2AFM0k/lib/python3.6/site-packages/django/contrib/admin/static", but I have no clue why it's looking in here.

Below I've provided my settings.py file. My file hierarchy is a mess, because doing collectstatic generated a whole bunch of static files into a staticfiles folder, but I don't know where they came from or what their purpose is. I have the style sheet in a static folder, but this doesn't seem to be being called anymore.

What I would like to know is this: what am I supposed to change either in my settings or in my file hierarchy so that main.css is found?

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'menus.apps.MenusConfig',
    'events.apps.EventsConfig',
    'users.apps.UsersConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
            os.path.join(BASE_DIR, 'users/templates'),
            os.path.join(BASE_DIR, 'events/templates'),
            os.path.join(BASE_DIR, 'menus/templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

DEBUG_PROPAGATE_EXCEPTIONS = True

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')

P.S. I have tried using whitenoise rather unsuccessfully as well.

I should also mention, when I look at the log files, I get the ValueError: Missing staticfiles manifest entry for … message referenced here, http://whitenoise.evans.io/en/stable/django.html#why-do-i-get-valueerror-missing-staticfiles-manifest-entry-for .

Working version of settings.py:

DEBUG = False

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'menus.apps.MenusConfig',
    'events.apps.EventsConfig',
    'users.apps.UsersConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
            os.path.join(BASE_DIR, 'users/templates'),
            os.path.join(BASE_DIR, 'events/templates'),
            os.path.join(BASE_DIR, 'menus/templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

DEBUG_PROPAGATE_EXCEPTIONS = True

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Upvotes: 1

Views: 1850

Answers (3)

rahul.m
rahul.m

Reputation: 5854

Basically,

WhiteNoise works with any WSGI-compatible app but has some special auto-configuration features for Django.

WhiteNoise takes care of best-practices for you, for instance:

  • Serving compressed content (gzip and Brotli formats, handling Accept-Encoding and Vary headers correctly)
  • Setting far-future cache headers on content which won’t change

Add this line wherever you like in settings.py

 STATICFILES_STORAGE = ‘whitenoise.storage.CompressedManifestStaticFilesStorage’

Upvotes: 0

TechSavy
TechSavy

Reputation: 1340

In Debug = False, try adding urls for static files in your project dir's url.py file:

from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls.static import static
from django.conf import settings
from django.views.static import serve

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^', include('app.urls')),

    re_path(r'^static/(?P<path>.*)$', serve,
            {'document_root': settings.STATIC_ROOT}),
] 

Update:

By adding above in project urls.py file, Django will inspect your STATIC_URL setting and wire up the view to serve static files accordingly.

Further, as stated in the docs, when in production mode (i.e., DEBUG = False), you should be using your web server to serve static files, not django. For this reason, staticfiles will refuse to serve your assets if DEBUG = False.

Upvotes: 7

Sebastian
Sebastian

Reputation: 96

In my app on Heroku I used instructions from https://docs.djangoproject.com/en/1.11/howto/static-files/. In settings.py I have configured:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/' 
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] 
STATIC_ROOT = os.path.join(BASE_DIR, 'collectstatic') 
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

I have also used this command to copy all files from your static folders into the STATIC_ROOT directory: python manage.py collectstatic

Upvotes: 0

Related Questions