'Images from database not displaying in Heroku Django after hosting
I have few images in my SQLite database which I will be changing from admin panel over a period of time. I have hosted the django app in heorku(free service). All the static images are displaying (The one's not in database), but the uploaded images are not displaying. I have uploaded the image before deploying. The description for each image is being displayed but the image is not. I am using whitenoise and have viewed multiple other answers and they have not worked
settings.py:
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',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
BASE_DIR / "static",
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
if os.getcwd() == '/app':
DEBUG = False
html template:
{% extends 'base/main.html' %}
{% load static %}
{% block content %}
<div class="container">
<div class="row my-5">
{% for image in images %}
<div class="col-sm col-md-4 col-lg-4 col-xl-4 my-3">
<div class="card" >
<img loading='lazy' src="{{image.image.url}}" class="img card-img-top my-2" alt="{{image.title}}">
<div class="card-body">
<p class="card-text">{{image.title}} </p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
models.py :
class Gallery(models.Model):
image = models.ImageField(upload_to ='uploads/')
title = models.CharField(max_length=100)
def __str__(self):
return f'{self.title}'
Edit : I have hosted from Github and not from Heroku CLI.
Solution 1:[1]
Add this line in settings.py
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
If there is django_heroku.settings(locals())
in settings.py remove it.
Add this line in settings.py if not added.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age = 600)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lubna shaikh |