0
0
Djangoframework~15 mins

Serving media in development in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Serving media in development
📖 Scenario: You are building a Django website that allows users to upload profile pictures. During development, you want to serve these uploaded images from your local computer so you can see them in the browser without setting up a full web server.
🎯 Goal: Set up Django to serve media files during development by configuring the media URL and root, and updating the URL patterns to serve media files correctly.
📋 What You'll Learn
Create a MEDIA_URL setting with the value "/media/" in settings.py
Create a MEDIA_ROOT setting pointing to a directory named media inside the project base directory
Import static and settings in urls.py
Add a URL pattern to serve media files during development using static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
💡 Why This Matters
🌍 Real World
Websites often allow users to upload images or files. During development, serving these files locally helps you test and see changes immediately.
💼 Career
Knowing how to serve media files in Django is essential for backend developers working on user-generated content features.
Progress0 / 4 steps
1
Add MEDIA_URL setting
In settings.py, create a variable called MEDIA_URL and set it to the string "/media/".
Django
Need a hint?

The MEDIA_URL is the URL prefix for media files served by Django during development.

2
Add MEDIA_ROOT setting
In settings.py, create a variable called MEDIA_ROOT that uses BASE_DIR joined with the string "media" using os.path.join. Make sure to import os if not already imported.
Django
Need a hint?

The MEDIA_ROOT is the folder on your computer where uploaded files will be stored.

3
Import static and settings in urls.py
In urls.py, import static from django.conf.urls.static and import settings from django.conf.
Django
Need a hint?

You need these imports to add URL patterns for serving media files during development.

4
Add media serving URL pattern
At the end of urls.py, add this line to the urlpatterns list: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to serve media files during development.
Django
Need a hint?

This line tells Django to serve files from the MEDIA_ROOT folder when URLs start with MEDIA_URL during development.