0
0
Djangoframework~30 mins

MEDIA_URL and MEDIA_ROOT in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Configuring MEDIA_URL and MEDIA_ROOT in Django
📖 Scenario: You are building a Django website where users can upload images. To make sure these images are saved and served correctly, you need to set up the right settings for media files.
🎯 Goal: Set up the Django settings to handle media files by defining MEDIA_URL and MEDIA_ROOT. This will allow your website to store uploaded files in a folder and serve them through a URL.
📋 What You'll Learn
Create a variable MEDIA_URL with the value "/media/" in settings.py.
Create a variable MEDIA_ROOT that points to a folder named media inside the project directory using BASE_DIR.
Use os.path.join to build the MEDIA_ROOT path.
Add the necessary import for os if not already present.
💡 Why This Matters
🌍 Real World
Websites often let users upload images or files. MEDIA_URL and MEDIA_ROOT help store and serve these files correctly.
💼 Career
Knowing how to configure media files is essential for Django developers working on real-world projects involving user content.
Progress0 / 4 steps
1
Import os and define BASE_DIR
In your settings.py file, import the os module and create a variable called BASE_DIR that uses os.path.dirname(os.path.dirname(os.path.abspath(__file__))) to get the project directory path.
Django
Need a hint?

Use import os at the top. Then set BASE_DIR using os.path.dirname twice on os.path.abspath(__file__).

2
Define MEDIA_URL variable
Add a variable called MEDIA_URL in settings.py and set it to the string "/media/".
Django
Need a hint?

Just create a variable MEDIA_URL and assign it the string "/media/".

3
Define MEDIA_ROOT using os.path.join
Create a variable called MEDIA_ROOT that uses os.path.join to join BASE_DIR and the string "media". This sets the folder where uploaded files will be saved.
Django
Need a hint?

Use os.path.join(BASE_DIR, "media") to build the path for MEDIA_ROOT.

4
Add media URL serving in urls.py
In your project's urls.py, import settings and static from django.conf and django.conf.urls.static respectively. Then add this line at the end of urlpatterns: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to serve media files during development.
Django
Need a hint?

Import settings and static. Then add + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to urlpatterns.