Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Web Development with Django

You're reading from  Web Development with Django

Product type Book
Published in Feb 2021
Publisher Packt
ISBN-13 9781839212505
Pages 826 pages
Edition 1st Edition
Languages
Authors (5):
Ben Shaw Ben Shaw
Profile icon Ben Shaw
Saurabh Badhwar Saurabh Badhwar
Profile icon Saurabh Badhwar
Andrew Bird Andrew Bird
Profile icon Andrew Bird
Bharath Chandra K S Bharath Chandra K S
Profile icon Bharath Chandra K S
Chris Guest Chris Guest
Profile icon Chris Guest
View More author details

Table of Contents (17) Chapters

Preface
1. Introduction to Django 2. Models and Migrations 3. URL Mapping, Views, and Templates 4. Introduction to Django Admin 5. Serving Static Files 6. Forms 7. Advanced Form Validation and Model Forms 8. Media Serving and File Uploads 9. Sessions and Authentication 10. Advanced Django Admin and Customizations 11. Advanced Templating and Class-Based Views 12. Building a REST API 13. Generating CSV, PDF, and Other Binary Files 14. Testing 15. Django Third-Party Libraries 16. Using a Frontend JavaScript Library with Django

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 2021 Publisher: Packt ISBN-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.
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}