Reader small image

You're reading from  Web Development with Django

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781839212505
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
Ben Shaw
Ben Shaw
author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

Saurabh Badhwar
Saurabh Badhwar
author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Bharath Chandra K S
Bharath Chandra K S
author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

Chris Guest
Chris Guest
author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest

View More author details
Right arrow

8. Media Serving and File Uploads

Overview

This chapter starts by introducing you to media files and then teaching you how to set up Django to serve them. Once you have understood this, you will learn how to build a form in HTML that can upload files to a view for storage to disk. To enhance this process and reduce the amount of code, you will use Django forms to generate and validate a form and learn how to process file uploads through it. You will then look at some enhancements that Django provides specifically for working with image files and use the Python Imaging Library to resize an image. You will then create a model that uses FileField and ImageField to store a file and image respectively and upload to it using a Django form. After this, you will build a ModelForm instance automatically from the model and save the model and the files using just one line of code. At the end of this chapter, you will enhance the Bookr app by adding a cover image and book excerpt to the...

Introduction

Media files refer to extra files that can be added after deployment to enrich your Django application. Usually, they are extra images that you would use in your site, but any type of file (including video, audio, PDF, text, documents, or even HTML) can be served as media.

You can think of them as somewhere between dynamic data and static assets. They are not dynamic data that Django generates on the fly, like when rendering a template. They also are not the static files that are included by the site developer when the site is deployed. Instead, they are extra files that can be uploaded by users or generated by your application for later retrieval.

Some common examples of media files (that you will see in Activity 8.01, Image and PDF Uploads of Books, later in this chapter) are book covers and preview PDFs that can be attached to a Book object. You can also use media files to allow users to upload images for a blog post or avatars for a social media site. If you wanted...

Settings for Media Uploads and Serving

In Chapter 5, Serving Static Files, we looked at how Django can be used to serve static files. Serving media files is quite similar. Two settings must be configured in settings.py: MEDIA_ROOT and MEDIA_URL. These are analogous to STATIC_ROOT and STATIC_URL for serving static files.

  • MEDIA_ROOT

    This is the path on the disk where the media (such as uploaded files) will be stored. As with static files, your web server should be configured to serve directly from this directory, to take the load off Django.

  • MEDIA_URL

    This is similar to STATIC_URL, but as you might guess, it's the URL that should be used to serve media. It must end in a /. Generally, you will use something like /media/.

    Note

    For security reasons, the path for MEDIA_ROOT must not be the same as the path for STATIC_ROOT, and MEDIA_URL must not be the same as STATIC_URL. If they were the same, a user might replace your static files (such as JavaScript or CSS files) with malicious...

Context Processors and Using MEDIA_URL in Templates

To use MEDIA_URL in a template, we could pass it in through the rendering context dictionary, in our view. For example:

from django.conf import settings
def my_view(request):
    return render(request, "template.html",\
                  {"MEDIA_URL": settings.MEDIA_URL,\
                   "username": "admin"})

This will work, but the problem is that MEDIA_URL is a common variable that we might want to use in many places, and so we'd have to pass it through in practically every view.

Instead, we can use a context processor, which is a way of adding one or more variables automatically to the context dictionary on every render call.

A context processor is a function that accepts...

File Uploads Using HTML Forms

In Chapter 6, Forms, we learned about HTML forms. We discussed how to use the method attribute of <form> for GET or POST requests. Though we have only submitted text data using a form so far, it is also possible to submit one or more files using a form.

When submitting files, we must ensure that there are at least two attributes on the form: method and enctype. You may still also need other attributes, such as action. A form that supports file uploads might look like this:

<form method="post" enctype="multipart/form-data">

File uploads are only available for POST requests. They are not possible with GET requests as it would be impossible to send all the data for a file through a URL. The enctype attribute must be set to let the browser know it should send the form data as multiple parts, one part for the text data of the form, and separate parts for each of the files that have been attached to the form. This encoding...

Storing Files on Model Instances

So far, we have manually managed the uploading and saving of files. You can also associate a file with a model instance by assigning the path to which it was saved to a CharField. However, as with much of Django, this capability (and more) is already provided with the models.FileField class. FileField instances do not actually store the file data; instead, they store the path where the file is stored (like a CharField would), but they also provide helper methods. These methods assist with loading files (so you do not have to manually open them) and generating disk paths for you based on the ID of the instance (or other attributes).

FileField can accept two specific optional arguments in its constructor (as well as the base Field arguments, such as required, unique, help_text, and so on):

  • max_length: Like max_length in the form's ImageField, this is the maximum length of the filename that is allowed.
  • upload_to: The upload_to argument...

Summary

In this chapter, we added the MEDIA_ROOT and MEDIA_URL settings and a special URL map to serve media files. We then created a form and a view to upload files and save them to the media directory. We saw how to add the media context processor to automatically have access to the MEDIA_URL setting in all our templates. We then enhanced and simplified our form code by using a Django form with a FileField or ImageField, instead of manually defining one in HTML.

We looked at some of the enhancements Django provides for images with the ImageField, and how to interact with an image using Pillow. We showed an example view that would be able to serve files that required authentication, using the FileResponse class. Then, we saw how to store files on models using the FileField and ImageField and refer to them in a template using the FileField.url attribute. We were able to reduce the amount of code we had to write by automatically building a ModelForm from a model instance. Finally...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web Development with Django
Published in: Feb 2021Publisher: PacktISBN-13: 9781839212505
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest