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.
You saved my life!!