In this tutorial, we will go over how to set up MEDIA_ROOT
and MEDIA_URL
in your Django settings. Django uses these settings to handle files uploaded by users.
By the end of this tutorial, you will:
- Understand the purpose of MEDIA_ROOT
and MEDIA_URL
- Be able to configure these settings in your Django project
Prerequisites:
- Basic understanding of Django
- Django installed on your machine
MEDIA_ROOT
is the absolute filesystem path to the directory that will hold user-uploaded files. MEDIA_URL
is the URL Django uses to access these files.
To set these up, you will need to modify your Django project's settings file (settings.py
).
Keep your media files separate from your static files. This can make your project easier to manage as it grows.
Here's how you can set up MEDIA_ROOT
and MEDIA_URL
:
# settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# MEDIA_ROOT is where uploaded files will be stored.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# MEDIA_URL is how you'll access these uploaded files.
MEDIA_URL = '/media/'
In this example, MEDIA_ROOT
is set to a directory named media
in your project's base directory, and MEDIA_URL
is set to /media/
. When a user uploads a file, Django will store it in the media
directory, and you can access it at your-domain.com/media/.
This tutorial covered how to set up MEDIA_ROOT
and MEDIA_URL
in your Django project. You learned that MEDIA_ROOT
is where Django stores user-uploaded files and MEDIA_URL
is how Django accesses those files.
For more, refer to Django's official documentation on managing files:
Set up MEDIA_ROOT
and MEDIA_URL
in a new Django project.
Upload a file using Django's FileField
or ImageField
and try to access it through the URL Django generates.
Solutions:
Refer to the code example in section 3.
An example of how to use FileField
:
# models.py
from django.db import models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
When you upload a file through this FileField
, Django will store it in the directory specified by upload_to
(relative to MEDIA_ROOT
), and you can access it at MEDIA_URL/documents/<year>/<month>/<day>/<filename>
.
Remember to practice and experiment on your own for better understanding. Happy coding!