q Image not loading in hosting/production while DEBUG = TRUE in DJANGO
Image not loading in hosting/production while DEBUG = TRUE in DJANGO

Image not loading in hosting/production while DEBUG = TRUE in DJANGO

When you're hosting your Django application in a production environment, images may not load even with DEBUG = Truedue to the following reasons:


1. Static and Media File Configuration

In a production environment, Django does not serve static or media files automatically, even when DEBUG = True. You need to explicitly configure your web server (e.g., Nginx, Apache) to serve these files.

Solution

  • Configure MEDIA_URL and MEDIA_ROOT in settings.py:

    MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media'

  • Add URL Patterns for Media Files in urls.py: When DEBUG = True, add a route to serve media files during development.

    from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT

 

 

2. If all this code has been added and still not loading add the following:

 

from django.contrib import admin

from django.urls import path, include, re_path

from django.conf import settings

from django.conf.urls.static import static

from django.views.static import serve

urlpatterns = [

path('admin/', admin.site.urls),

re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),

re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),

] if settings.DEBUG:

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Import this this re_path and server

from django.urls import path re_path

from django.views.static import serve

And add this line inside urlpatterns:

re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),

re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),