About Lesson
Media files are files uploaded by users (e.g., images, PDFs, videos). Django doesn’t automatically serve media files in development or production, but it provides an easy way to handle media uploads and configure settings to store and access these files.
Configuring Media Files in Django
You need to specify two important settings in your settings.py
to manage media files:
MEDIA_URL
: The URL path for accessing media files.MEDIA_ROOT
: The file system path where uploaded media files will be stored.
MEDIA_URL
: This is the base URL that Django will use to serve media files (e.g.,/media/
).MEDIA_ROOT
: This is the absolute file system path where media files will be stored, such as user-uploaded images and documents.
Example of Media File in Django Template
Handling File Uploads in Django
Django provides forms to handle file uploads. The model field used to store uploaded files is FileField
or ImageField
for images.
Example of Model with Media File:
- The
upload_to
argument in theImageField
specifies the subdirectory where files will be uploaded, relative to theMEDIA_ROOT
directory.
Handling File Upload in Forms
You need to include an HTML form with enctype="multipart/form-data"
to allow users to upload files.
Example of Form for Uploading Files:
Example of Template for Uploading Files:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
request.FILES
: This allows you to access the uploaded files in your form.
Join the conversation