Welcome to this comprehensive guide on using media files in Django templates! In this lesson, we'll learn how to handle images, videos, and other files in your Django projects, making your websites more dynamic and engaging.
Media files are any types of files like images, videos, audios, PDFs, and more that can be used to enrich the content of your Django project. These files are typically stored in the MEDIA_ROOT and MEDIA_URL directories in your Django project.
Before we dive into using media files in templates, let's set up the media files directory structure in our Django project.
MY_PROJECT/
my_app/
templates/
my_app/
index.html
static/
my_app/
media/
images/
videos/
migrations/
...In the above directory structure, my_app is the name of your Django app, and media is the directory where we'll store our media files.
To allow users to upload media files, we'll create a simple form. Here's how to create an image upload form.
from django import forms
from django.conf import settings
from django.core.files.storage import default_storage
class ImageUploadForm(forms.Form):
image = forms.ImageField(
label="Select an image",
help_text="Max. 4 MB",
max_length=None,
allow_empty_file=False,
required=False
)
def save(self, commit=True):
img = self.cleaned_data['image']
img_name = default_storage.save(img.name, img)
img_url = settings.MEDIA_URL + img_name
if commit:
default_storage.save(img_name, img)
return img_urlTo display media files in templates, we'll use the {% load static %} tag to load the static files, and the <img> tag to display images.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Media Files in Templates</title>
</head>
<body>
<h1>Welcome to Django Media Files Tutorial</h1>
<form method="post">
{% csrf_token %}
{% for form in formset %}
{{ form.as_p }}
{% empty %}
<p>No forms available.</p>
{% endfor %}
<button type="submit">Save</button>
</form>
{% if image %}
<img src="{% static image %}" alt="Uploaded Image">
{% endif %}
</body>
</html>In the above example, {% static image %} refers to the uploaded image, and {% if image %} checks if an image has been uploaded.
Where do we store media files in a Django project?
That's it for this section! In the next part, we'll learn how to display videos and other media files in our Django templates. Keep learning and coding! π‘π―