Search code examples
djangodjango-staticfilesdjango-deployment

404 for static images and media in Django in Production Mode


I am beginner in Django

I am trying to run my application on Debug=False mode to simulate the production environment, I have added all the static url, and roots. My program is generating the static images in real-time from the video passed to the application during runtime.

This is working as expected in the development mode but I am getting 404 for images and videos in the production mode other stuff like bootstrap and JS are getting loaded fine.

Earlier bootstrap and js was also not loading then I installed Whitenose and things start working, but now images and videos and giving 404.

Link to the application code: https://github.com/abhijitjadhav1998/Deepfake_detection_using_deep_learning/tree/master/Django%20Application

Further to this application, I have added the STATIC_ROOT in the settings.py

and added os.system('python manage.py collectstatic --noinput') in the views.py folder to populate the static path with images and videos before sending the response to the html page.

But still I am getting the 404, I also checked the file with same name is avaliable in the location.

I am getting the below error:

enter image description here Error from the console: Able to load the js, bootstrap but able to load the images and video enter image description here

Code from settings.py that I have added

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.abspath(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

DEBUG = False

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    "whitenoise.runserver_nostatic",
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ml_app.apps.MlAppConfig',
]

MIDDLEWARE = [
        "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

ROOT_URLCONF = 'project_settings.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(PROJECT_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media'
            ],
        },
    },
]

WSGI_APPLICATION = 'project_settings.wsgi.application'

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(PROJECT_DIR, 'db.sqlite3'),
    }
}

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'models')

STATICFILES_DIRS = [
        os.path.join(PROJECT_DIR, 'static'),
        os.path.join(PROJECT_DIR, 'models'),
    ]

STATIC_ROOT = os.path.join(PROJECT_DIR, 'staticfiles')

CONTENT_TYPES = ['video']
MAX_UPLOAD_SIZE = "104857600"

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'uploaded_videos')

EDIT :

I added all the uploaded_images into static/images/uploaded_images, this is loading the static images but now the issue is it is not loading the images from a for loop in html file

For below the images gets loaded as expected.

  <div id="preprocessed_images" class="col-12 mt-4 mb-2">
    {% for each_image in preprocessed_images %}
    <img src="{%static 'images/uploaded_images/uploaded_file_1651078566_cropped_faces_5.png'%}" class="preprocess"
      width=auto height="250" />

    {%endfor%}
  </div>

For below it is still giving 404. the value of each image is each_image = images/uploaded_images/uploaded_file_1651078566_cropped_faces_5.png

  <div id="preprocessed_images" class="col-12 mt-4 mb-2">
    {% for each_image in preprocessed_images %}

    <img src="{%static each_image%}" class="preprocess" width=auto height="250" />

    {%endfor%}
  </div>

I am loading meadia files like this but still its 404

<video height="320" width="640" id="predict-media" controls>
      <source src="{{MEDIA_URL}}{{original_video}}" type="video/mp4" codecs="avc1.4d002a" />
    </video>

Solution

  • Django doesn't serve static files in production automatically we will need a web server like apache/Nginx to serve the static files.

    I was able to serve the static files by hosting the application on Nginx as a reverse proxy server and Gunicorn to handle Django requests. I used docker to host the application.

    Step by step guide is given in this Blog