Performance: Serving media in development
This affects page load speed and responsiveness when loading images, videos, or other media files during development.
Configure MEDIA_URL and MEDIA_ROOT in settings.py and use django.views.static.serve in urls.py only during development to serve media files efficiently.
Using Django's default static file serving in development without configuring media URL and root properly, e.g., not using django.views.static.serve or not setting MEDIA_URL and MEDIA_ROOT correctly.| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default Django dev server serving media without config | Minimal | 0 | High due to delayed media load | [X] Bad |
| Configured MEDIA_URL and MEDIA_ROOT with django.views.static.serve | Minimal | 0 | Lower paint delay due to faster media delivery | [OK] Good |
urls.py during development?static from django.conf.urls.static and settings from django.conf.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to serve media files during development.urls.py snippet with DEBUG=True:
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
urlpatterns = [path('home/', lambda request: None)]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
What happens when you visit a media file URL like /media/image.jpg?DEBUG=True, Django serves media files using the static helper in development.static() function adds URL patterns to serve files from MEDIA_ROOT at MEDIA_URL.urls.py to serve media files but get 404 errors when accessing media URLs:
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ... ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)What is the most likely cause?
static() when DEBUG=True. If False, 404 occurs.urls.py?DEBUG=True), not in production.static() call inside an if settings.DEBUG: block to add media URLs only in development.Pass the test and this pattern moves unknown