Search code examples
pythondjangodjango-urlsdjango-staticfilesdjango-media

Django media file page not found


So, I'm trying to follow Django documentation about the static files and media files

I have a clean Django installation and I want to add the media folder. What I've done? I've changed the urls.py inside the project (not the app) and the settings.py as below

settings.py

STATIC_URL = 'static/'
MEDIA_URL = 'media/'

MEDIA_ROOT = BASE_DIR / "media"

STATICFILES_DIRS = [
    BASE_DIR / "static",
]

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

But I got the

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in web_project.urls, Django tried these URL patterns, in this order:

admin/ ^media/(?P.*)$ The empty path didn’t match any of these.

I've also tried adding the 'django.template.context_processors.media' into TEMPLATES and using os as below

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

but nothing changes

What it could be?


Solution

  • Getting this error is the expected behavior because when you add a path to urlpatterns in urls.py in your example + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) you'll no more get access to http://127.0.0.1:8000/ (it just renders a “Congratulations!” page, with a rocket taking off. It worked! ) unless you specify a view to this empty path (which you didn't)

    In your case, there is no URL leading to http://127.0.0.1:8000/ . the only paths you get access to are :

    1- http://127.0.0.1:8000/admin/ for the admin page

    2 - http://127.0.0.1:8000/media/(?P<path>.*)$ to access you media files for example, if you have an image img.png in media folder you can access http://127.0.0.1:8000/media/img.png and view your image