Home > OS >  unable to load photos in Django after deploying to heroku
unable to load photos in Django after deploying to heroku

Time:10-22

I have made a portfolio blog website using Django. it works perfectly when running it locally but after I deployed it to Heroku, accessing the portfolio redirected me to a 500 server error. I turned on debug mode and when I did the same, it didn't throw a 500 server error, however, the pictures won't load. this is very confusing and help will be very appreciated...

settings.py

    from pathlib import Path
import os
from dotenv import load_dotenv
load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = True


ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'projects',
    'blog',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    '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',
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'personal_portofolio.urls'

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


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,  'templates'),
)

import django_heroku
django_heroku.settings(locals())

wsgi.py

import os

from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'personal_portofolio.settings')

application = get_wsgi_application()
application = WhiteNoise(application)

what my project directory looks like:

C:.
├───blog
│   ├───migrations
│   │   └───__pycache__
│   ├───templates
│   └───__pycache__
├───personal_portofolio
│   ├───templates
│   └───__pycache__
├───projects
│   ├───migrations
│   │   └───__pycache__
│   ├───static
│   │   └───img
│   ├───templates
│   └───__pycache__
└───staticfiles
    └───admin
        ├───css
        │   └───vendor
        │       └───select2
        ├───fonts
        ├───img
        │   └───gis
        └───js
            ├───admin
            └───vendor
                ├───jquery
                ├───select2
                │   └───i18n
                └───xregexp

Edit: after setting DEBUG_PROPAGATE_EXCEPTIONS to True, I am getting this error in the Heroku logs ValueError: Missing staticfiles manifest entry for 'staticfiles/project1.png'

CodePudding user response:

Your settings.py seems fine, try adding this code to project-name/urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns  = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # add static file URL to django urlpatterns

If your trying to host media files note that Heroku does not support media hosting you might need to connect your Django application with something like amazon s3 bucket. You can find an article about it here.

Please accept the answer if this works for you. Happy coding!

  • Related