liveBook · Manning

MEDIA_URL

As explained in Django in Action

MEDIA_URL is the Django setting that specifies the base URL used to serve media files.

MEDIA_URL defines the base URL for uploaded media files. Setting it to /media/ means a file served through this media location begins with that path. section 7.4.1

Configure uploads in RiffMates

In settings.py, pair the public URL with the server-side directory: MEDIA_ROOT = BASE_DIR.parent / 'outside/RiffMates/uploads' and MEDIA_URL = '/media/'. During development, add static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to the URL configuration when DEBUG is true. Django can then serve uploaded files at /media/ without requiring a separate web server. section 7.4.1

Keep these boundaries in mind:

  • MEDIA_URL is the URL-facing location; MEDIA_ROOT is the filesystem location where uploaded files live. section 7.4.1
  • Files under MEDIA_URL are publicly downloadable by default, including by users who are not logged in. section 7.4.4
  • For restricted downloads, store files outside MEDIA_ROOT and serve them through controlled views or web-server hand-offs instead of exposing them under /media/. section 7.4.4
# RiffMates/RiffMates/settings.py
...
MEDIA_ROOT = BASE_DIR.parent / 'outside/RiffMates/uploads'  #1
MEDIA_URL = '/media/'  #2

See the paired MEDIA_ROOT and MEDIA_URL settings used for the upload directory. section 7.4.1

Listing 7.15 Serve uploaded files as if they were static files, in development mode
# RiffMates/RiffMates/urls.py
...
from django.conf import settings  #1
from django.conf.urls.static import static  #2
...
if settings.DEBUG: #3
    urlpatterns += static(settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT)  #4

See the DEBUG-only URL configuration that serves MEDIA_URL from MEDIA_ROOT during development. section 7.4.1

How Django in Action covers it

How deep it goes
Explains the setting, pairs it with MEDIA_ROOT, and demonstrates DEBUG-only development serving before deferring production delivery to a web server.
Examples
Uses RiffMates paths, the /media/ prefix, settings.py, and a DEBUG-guarded static() URL configuration.
What it assumes
Assumes familiarity with Django settings and URL configuration while teaching the distinction between URL and filesystem paths.
What you can do after
Operate/configure Django uploads by mapping a media URL to a filesystem directory during development.
How it connects
Connects MEDIA_URL to MEDIA_ROOT, uploaded files, static files, DEBUG, URL configuration, and web servers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.