Search code examples
djangoproductiondjango-staticfiles

Django is loading static files but not image that are stored from backend in production


As the title says, after I changed DEBUG to False, the image that is uploaded from the admin panel are not loading. However, other static files like css files and images that are loaded only from HTML side are rendered properly.

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('marathon.urls', namespace='homepage')),
    path('accounts/', include('allauth.urls')),
    path('logout', LogoutView.as_view(), name='logout'),
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

html file that renders image

    <div class="js-billboard">
        {% for slide in slider %}
            <div class="billboard__item">
                <figure><img src="{{ slide.image.url }}" alt="Mountain Marathon"></figure>
                <div class="billboard__detail">
                    <div class="grid-container">
                        <div class="grid-x grid-padding-x">
                            <div class="col-12 cell">
                                <h2>{{ slide.title }}</h2>
                                <p><span>{{ slide.description }}</span></p>
                                <a href="{{ slide.link }}" class="button">{{ slide.link_title }}</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>

Solution

  • I assume you have the following line of code in your projects urls.py

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

    Please note that static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) for your media urls will only be added to your urlpatterns list if DEBUG=True in this case. Django doesn't serve media files in Production or when the DEBUG=False

    I would suggest using a online storage API like AWS3, cloudinary or even firebase. These do offer the capability of serving media files whether DEBUG=True or DEBUG=False.