MEDIA_URL and MEDIA_ROOT help your Django app handle user-uploaded files like images or documents. They tell Django where to store these files and how to access them in a browser.
0
0
MEDIA_URL and MEDIA_ROOT in Django
Introduction
When users upload profile pictures to your website.
When you want to save and show documents uploaded by users.
When you need to serve media files during development.
When organizing media files separately from your code files.
Syntax
Django
MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL is the URL path prefix for media files.
MEDIA_ROOT is the absolute filesystem path where media files are stored.
Examples
This example changes the URL and folder name to 'uploads' instead of 'media'.
Django
MEDIA_URL = '/uploads/' MEDIA_ROOT = BASE_DIR / 'uploads'
This example uses an absolute path outside the project folder for storing media files.
Django
MEDIA_URL = '/user_media/' MEDIA_ROOT = '/var/www/user_media/'
Sample Program
This simple script shows how MEDIA_URL and MEDIA_ROOT are set using BASE_DIR. MEDIA_URL is the web path prefix, and MEDIA_ROOT is the folder path on your computer.
Django
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' print(f"MEDIA_URL is set to: {MEDIA_URL}") print(f"MEDIA_ROOT is set to: {MEDIA_ROOT}")
OutputSuccess
Important Notes
Always use an absolute path for MEDIA_ROOT to avoid confusion.
During development, you need to configure your URL patterns to serve media files using MEDIA_URL.
In production, media files are usually served by the web server, not Django directly.
Summary
MEDIA_URL defines the URL prefix to access media files in the browser.
MEDIA_ROOT defines the folder on your computer where media files are saved.
They work together to manage user-uploaded files in Django projects.