Search code examples
djangodjango-staticfilesdjango-mediadjango-uploads

Django Media Directory HTTP 404 for Uploaded Images


My project structure is:

- api/
    - urls.py
    ...
- avatars/
    - 16701016.jpg
    - 16701019.jpg
    ...
- frontend/
    - static/
        - frontend/
    - templates/
    - urls.py
    ...
- website/
    - settings.py
    - urls.py
    ...

Part of the settings.py file:

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.abspath('../avatars/')
MEDIA_URL = '/avatars/'

The contents of /website/urls.py :

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls')),
    re_path(r'^.*', include('frontend.urls'))
]

Now I need to access the /avatars/*.jpg files via URL like http://127.0.0.1:8000/avatars/*.jpg

But It is not working (Just 404). What is the problem?


Solution

    1. Change the MEDIA_ROOT value from:

      MEDIA_ROOT = os.path.abspath('../avatars/')  
      

      to:

      MEDIA_ROOT = os.path.abspath('avatars')
      
    2. And also append the following code in urls.py:

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