Django Media Files
Working with simple media uploads and serving these media files
In Django, media files can be defined as those files which are uploaded by the users. For examples:
- Profile Picture uploads
- File Uploads and many more ...
Configurations
On our Django settings settings.py
we add MEDIA_URL
and MEDIA_ROOT
settings
MEDIA_URL='/media/'
MEDIA_ROOT = BASE_DIR /'media'
or
MEDIA_ROOT = '/var/www/media/'
Note:
MEDIA_ROOT
is the folder where your file gets saved.
Creating a URL configurations so serve uploaded files
In static files serving, Django would provide us with a way to serve static files automatically, But to serve the media files we will need to create a URL configurations to serve all media files from MEDIA_ROOT
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# rest of project url patterns
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Note: we serve media files like this on local development environment only, on production servers we use a different approach. We serve these assets directly through the webserver.
Just to try if everything is working, you can create a sample file(
image.jpg
) inside theMEDIA_ROOT
directory, and check if Django is serving it at/media/image.jpg
Simple File Upload in Django
- When files are submitted from HTML form to server, the file data can be accessed from
request.FILES
on Django views.request.FILES
is a dict like object - Each key in
request.FILES
is the name from<input type="file" name="">
- It's mandatory for the HTML forms to have the attribute
enctype="multipart/form-data"
- Form must be submitted using
POST
method - Django has proper model fields
ImageField
andFileField
for handling file uploads - These uploaded files are stored on filesystem
(MEDIA_ROOT)
and only the reference of file is stored inImageField
orFileField
in Database. So basically these fields are abstraction created by Django to help us deal with file uploads but deep down they are just theCharField
on database side
Example: A basic file uploads, and handling the file uploads manually on the Django side
on HTML side,
<!-- image-uploads.html -->
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="image">
<input type="submit" value="submit">
</form>
on Django view side,
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
from django.shortcuts import render
def image_upload(request):
if request.method == 'POST' and request.FILES['image']:
image = request.FILES['image']
fs = FileSystemStorage()
# save the image on MEDIA_ROOT folder
file_name = fs.save(image.name, image)
# get file url with respect to `MEDIA_URL`
file_url = fs.url(file_name)
return HttpResponse(file_url)
else:
# render the form
return render(request, "image-uploads.html")
That't it, now we can process file uploads in Django, save it to the MEDIA_ROOT
location automatically using FileSystemStorage()
When using Django model and fields with
ImageFiled
orFileField
we don't need to perform the file processing/saving manually like we did just now. Simply we would assign the file to the field, and call the model.save() method like we generally do. I will talk about it in detail in some other tutorial.