I have a Django project deployed to Heroku. Locally, it works fine. However, there is a problem in production: the image files uploaded by the admin cannot be found and displayed.
The error message is:
Failed to load resource: the server responded with a status of 404 (Not Found)
and the URL that the server tried is something like this:
https://thawing-escarpment-####.herokuapp.com/image.png
To fix this, I attempted to use Amazon S3 as storage for the media files. I'm completely new at this, so I tried several tutorials and nothing worked.
Using this Heroku tutorial for reference, I created a bucket called my-website-assets
and then set up the configurations for Heroku:
heroku config:set AWS_ACCESS_KEY=xxx AWS_SECRET_KEY=yyy
heroku config:set S3_BUCKET = my-website-assets
and then modified the bucket CORS configuration:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>thawing-escarpment-####.herokuapp.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
In app/models.py
I have:
class SpotlightContent(models.Model):
title = models.CharField(max_length=300)
image = models.ImageField(upload_to="")
description = models.TextField()
In templates/home.html
:
{% for content in spotlight_contents %}
<img src="{{ content.image.url }}" alt="{{ content.title }}" width="140" height="140">
<p>{{ content.description }}</p>
{% endfor %}
In my settings.py
file I made changes to the MEDIA_URL
and MEDIA_ROOT
:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static', 'static_dirs'),
)
ADMIN_MEDIA_PREFIX = 'https://s3.amazonaws.com/my-website-assets/'
MEDIA_URL = 'https://s3.amazonaws.com/my-website-assets/'
MEDIA_ROOT = ''
After these changes, I logged back into the Django, added a new Spotlight object, and refreshed the web page. The image still could not be loaded, so I checked the source code:
<img src="https://s3.amazonaws.com/my-website-assets/test_icon.png" alt="Test" width="140" height="140">
<p>This is a test. Please work!</p>
Although the URL is an Amazon AWS one, the image resource could not be found, which leads me to believe that it was not added properly. Does anyone know how to get this to work? Thanks in advance.