Django not serving media files when hosted on render.

i deployed a webapp in Django on render.com but it is not loading the uploaded images. It will show up when i upload those again. but when i re deploy it wont show up again. this is only for uploaded images.
I guess it knows that there are images but it just wont show up.
i tried a lot from information from the internet and django documentations

urls.py

urlpatterns = [
    re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}),
    re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    path('',home_view, name='home'),
    path('about_us/', about_view, name='about'),
    path('projects/', project_view, name='projects'),
    path('project_detail/<str:name>', project_details),
    path('gallery/', gallery_view, name='gallery'),
    path('services', services_view, name='services'),
    path('testimonials/', testimonial_view , name='testimonial'),
    path('admin/', admin.site.urls),
] 
#urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)

#urlpatterns += staticfiles_urlpatterns()

settings.py

DEBUG = os.environ.get('D_MODE', 'True').lower() == 'True'

ALLOWED_HOSTS = ['*']
db_url = os.environ.get('DB_URL')
    DATABASES = {
        'default': dj_database_url.parse(db_url)
    }
STATIC_URL = "/static/"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

if DEBUG:
    STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

below is the screenshot of the page when loaded:

Hey there!
This is probably because the MEDIA files are being saved on disk on the render machine, but whenever you deploy a new change, your code can be running on a different machine that the one that was saved on disk.
This is stated on the 1st paragraph of the Persistent Disks documentation of render.

The default filesystem for services running on Render is ephemeral. Application data isn’t persisted across deploys and restarts, and this works just fine for most apps because they use managed databases to persist data.

  • You can, read the above documentation and see how you can have persistent disk storage; or
  • Use another cloud provider for this kind of storage (AWS S3 is a common choice). In this case, you’ll probably want to store your media files using something like django-storages.

Cheers!

I’ve been working to solve this for a week. Could you suggest any free hosting platforms with persistant storage? I only use render to show my clients theirs product and get feedback or is there any other way to do it?
Thanks alot…

I believe that AWS has a free tier that includes S3.
You can then use django-storages to upload/retrieve files from that.

1 Like