Skip to content

Instantly share code, notes, and snippets.

@jacobvalenta
Last active December 19, 2024 15:52
Show Gist options
  • Save jacobvalenta/bb24c2bd33b7f73d68a6e99161a5a29a to your computer and use it in GitHub Desktop.
Save jacobvalenta/bb24c2bd33b7f73d68a6e99161a5a29a to your computer and use it in GitHub Desktop.

Django developement media url misconfiguration

Error:

Your URL pattern [<URLPattern '^media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.

Explaination

static() returns a list of url paths, (not a url path).

Incorrect configuration

if settings.DEBUG:
    urlpatterns += [
        re_path(r'^static/(?P<path>.*)$', views.serve),
        static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    ]

Correct configuration

if settings.DEBUG:
    urlpatterns += [
        re_path(r'^static/(?P<path>.*)$', views.serve),
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Alternate correct configuration

if settings.DEBUG:
    urlpatterns += [
        path(r'^static/(?P<path>.*)$', views.serve),
    ]
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Best configuration

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    ... # Your URLs
]

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

Note: This is only for serving static and media files in development. Production use is lazy.

@Petrprogs
Copy link

You saved my life!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment