[Answered ]-How to write dynamic (Django) URLs for serving images using Whitenoise on Heroku?

1👍

I fixed the issue, but I don’t understand why. So if anyone can explain it, I’ll accept that answer. I have two root folders,static and staticfiles. Each had their own folders images and media. I removed all the existing images, made changes to the code (see below), and re-uploaded the images–and viola! It worked–and worked on Heroku.

STATIC_URL = '/static/'  # Didn't work
STATIC_URL = '/staticfiles/'  # Yes, worked

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_TMP = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'



MEDIA_URL = '/media/'     # Didn't work
MEDIA_URL = '/staticfiles/media/' # Yes, worked

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')     # Didn't work
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles/media/')     # Yes, worked
👤YCode

0👍

The first img tag you had is the correct way of pulling static files from your static directory. Whitenoise simply helps serve images/media files on Heroku servers but it isn’t needed for local development. To properly use static, however, you need to load static at the top of each template. Example:

<!-- template.html -->
{% extends 'base.html' %}
{% block content %}

{% load static %}

<!-- show static image -->
<img src="{% static 'images/hi.jpg' %}" alt="Hi!" />

<!-- show dynamically -->
<img src="{{ item.image.url }}" alt="{{ item.name }}">

{% endblock %}

Note that the actual path to the image, images/hi.jpg, is in single quotes so as to not conflict with the outside double quotes

Leave a comment