Programmingjoe
Programmingjoe

Reputation: 2249

Only Static IMAGES not showing up on Django application? Deployed to Heroku and using S3

I have a finished Django application that I am trying to push to production using Heroku and S3 but I have run into some confusion.

So far I have pushed the project to Heroku using git, I have pushed my Postgres database to the HerokuPostgres and that is working, and I have uploaded my static files (including css and images) to S3.

Currently, when you go to the Heroku application (https://foobar.herokuapp.com/) the page loads, the css works, and the database works. However, the static images are not showing up. Why could this be?

Here are a few lines from my settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '###',
        'USER': '###',
        'PASSWORD': '###',
        'HOST': '###',
        'PORT': '###',
    }
}

DATABASES = {'default': dj_database_url.config(default='postgres://foobar')}

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# MEDIA_ROOT = '/home/joe/Documents/exchange/Texchange/textchange/media/'

MEDIA_URL = '/media/'

# STATIC_ROOT = '/home/joe/Documents/exchange/Texchange/textchange/static/'

# STATIC_URL = '/static/'

AWS_STORAGE_BUCKET_NAME = 'bucketname'
AWS_ACCESS_KEY_ID = 'foobar'
AWS_SECRET_ACCESS_KEY = 'foobar'

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN

STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

I am just looking for some guidance as to why the images aren't showing up.

Note: Images uploaded by users are being uploaded to S3 and being displayed on the site but still my static images do not show up. How could uploaded images work fine but no other static images work?

Upvotes: 0

Views: 1916

Answers (2)

Nelson Bassey
Nelson Bassey

Reputation: 71

To enable images to load when DEBUG=False, do the following in your urls.py file

from django.conf.urls import url

from django.views.static import serve

and then add those two urls in urlpatterns:

url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),

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

assuming that your MEDIA_URL = 'media' and STATIC_URL='static'

Upvotes: 1

jcomeau_ictx
jcomeau_ictx

Reputation: 38412

serving static files is actually one of the things that Django makes incredibly complicated and fraught with hazard. the recommended way is here: https://docs.djangoproject.com/en/1.9/howto/static-files/, and here https://docs.djangoproject.com/en/1.9/howto/static-files/deployment/. I ended up making a show_static view and a pattern that matched the static pages, so just put url(static_pattern, views.show_static) in my urls.py.

Upvotes: 0

Related Questions