Building a Social Media App With Python 3 & Django Beginners Tutorial 16: Uploading Multiple Images

Video Tutorial

Code on Github

In this tutorial we will add the ability to upload multiple images to posts. We will just need to make a few changes to our models, form, views, and templates where we are already handling images. Let’s start with the models.py file.

Updating models.py

To make this work, we will need to add another model for the image. We can then add a ManyToMany field. This will allow us to store multiple images.

Updating Our Post Form

Next we need to update our post form, we are going to update the image widget. We can add the multiple attribute to allow the user to select multiple images. We also want to remove the image field from the Meta child class. We do this to prevent the form from saving the image field automatically. We will handle that manually in our view.

Updating the PostList View

Now let’s save the images and add them to the Post object. We will need to get the images and then loop over them and save them each as an Image object. Once we have an image object saved we can then add them to the ManyToMany field on the Post object. Finally we need to make sure we call the save functions to save everything to the database.

Showing Multiple Images in the Templates

Finally we need to update the templates to show multiple images. There are multiple ways we could go about handling this but I am going to just show them in a grid. We need to update the post list, post detail, and profile templates which are the templates that show posts. We can check if there are posts by checking if the length is greater than 0 and then we can get an iterable list by using post.image.all. Then we can loop over each image and display it on the page. This code will look the same on all of the templates.

This concludes this tutorial. We now should be able to upload multiple images to one post. There are a few more features we could add to this application. We will come back later to add those.