0
0
Djangoframework~5 mins

Serving media in development in Django

Choose your learning style9 modes available
Introduction

When you build a website, you often have pictures or files users upload. During development, Django needs a simple way to show these files so you can see them while working.

You want to test how uploaded images appear on your site before going live.
You need to check if user-uploaded files are saved and displayed correctly.
You are building a blog and want to preview photos attached to posts.
You want to see media files without setting up a full web server.
You are developing locally and want quick access to media files.
Syntax
Django
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # your url patterns here
]

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

This code goes in your main urls.py file.

It only works when DEBUG = True, which is usually during development.

Examples
This example shows adding media serving to a simple URL list with an admin path.
Django
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You can also specify media URL and root directly, but using settings is better for flexibility.
Django
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = []

if settings.DEBUG:
    urlpatterns += static('/media/', document_root='/path/to/media')
Sample Program

This Django URL configuration serves a simple home page and adds media file serving when in development mode.

Django
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from django.http import HttpResponse

# Simple view to test

def home(request):
    return HttpResponse('Hello, this is the home page.')

urlpatterns = [
    path('', home),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
OutputSuccess
Important Notes

Never use this method to serve media files in production. Use a proper web server like Nginx or Apache instead.

Make sure your MEDIA_URL and MEDIA_ROOT are set correctly in settings.py.

Serving media this way is only for convenience during development.

Summary

Serving media in development lets you see uploaded files easily while building your site.

Use Django's static() helper in urls.py with DEBUG=True.

Always switch to a real web server for media files when your site is live.