2

I am unable to load static files in production, whereas they work on local machine.

I have followed the steps in https://devcenter.heroku.com/articles/django-assets as well as the existing answers but I am not able to make it run. I am overlooking something and would like the community's assistance.

Here is the partial settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

ALLOWED_HOSTS = ['tryml.herokuapp.com','localhost']


# Application definition

INSTALLED_APPS = [
    'web.apps.WebConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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 = 'tryml.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'tryml.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/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.0/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.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

Here is the wsgi.py file:

import os

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tryml.settings")

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

Here is the html file trying to access the static content:

{% extends "web/base.html" %}
{% load static %}

{% block content %}

      <div>
        <img src="{% static 'web/img/target.jpg' %}" alt="Image could not be loaded"></img>
      </div>

{% endblock %}

Here is the project structure:

tryml
  --static
    --web
      --img
        --target.jpg
  --tryml
    --settings.py
    --wsgi.py
    --urls.py 
  --web(web app)
  --(urls,forms,templates,...)
  --manage.py
  --Procfile
  --requirements.txt
  --runtime.txt

One more observation, when I check the requests sent from my browser, it shows a 404 error for the static file(image) and says it tried to lookup here- ...herokuapp.com/static/web/img/target.jpg

Shouldn't it refer from STATIC_ROOT(staticfiles/web/img/target)?

EDIT-- The collectstatic command runs when the code is pushed on heroku,and it shows a successful copy step into app/staticfiles. Still, static file is not loading.

EDIT2--I ran the command python manage.py findstatic web/img/target.jpg as mentioned here: https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#findstatic

It returned the file location on local machine but on heroku, it says 'No matching file found for 'web/img/target.jpg'.' Why is it not being located even after a collectstatic command has run successfully? How does the production fetch of static files actually work? When I use {% static web/img/target.jpg %}, does it go to the STATIC_ROOT location to fetch it?

  • Did you check this https://stackoverflow.com/questions/31808874/gzip-not-working-in-django-with-whitenoise? – chiseledCoder May 29 '18 at 10:50
  • The OP there says that the static files work fine, the problem there is with the gzip. In my case, the static file isn't getting loading itself. Do you think they are related? – shreyas divan May 29 '18 at 11:23
  • Yes. Gzip is will not work until you have "Accept-Encoding: gzip" in your header. instead, try whitenoise.storage.CompressedManifestStaticFilesStorage – chiseledCoder May 29 '18 at 11:58
  • I already am getting "Accept-Encoding: gzip, deflate, br" in my request header. By changing the mentioned settings, I still get the same result.. – shreyas divan May 29 '18 at 14:51

2 Answers2

0

You have to serve the static file using nginx or you have to add path in urls py.

urlpatterns = [
            # ... the rest of your URLconf goes here ...
 ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
aman kumar
  • 3,086
  • 1
  • 17
  • 24
0

After doing 'find' on the remote heroku server from my machine, I came to know that the file is stored as 'target.JPG' and not 'target.jpg'.

I changed the access link accordingly in the template and it worked.

On the local machine, the CAPS do not seem to matter as I had already played around with them earlier.

Also, my git push to heroku never really changed the filename to 'target.jpg' because it doesn't consider changes in the caps of the filename unless told to as mentioned here - Changing capitalization of filenames in Git

Thank You.