The Django Multiple File Upload Chronicle

Ritwick Raj
AnitaB.org Open Source
2 min readJul 8, 2020

Working with Django seems so beautiful, with every bit of extraction done for you. Just import the function and use it. Be it sending emails or doing user authentication, everything becomes simple. But the problem is that with this level of abstraction comes the difficulty of implementing new features on your own. A similar problem was faced by me this week.

With the joy and happiness of clearing through the first phase of evaluation for GSoC with AnitaB.org, I was faced with the new issues for Phase 2. For one of the issues, I had to add multiple images field and resources field to a Meetup.

The Resources Field

The resources field for a meetup is a field where the links and details regarding the meetup are stored. The resources field was to be used for various purpose right from adding videos to images to text to hyperlinks. So to serve this purpose, the Portal Project Team decided to use the RichTextField provided by CkEditor.

Just in two steps one can add a RichTextField which adds html text to a field.

Below is a look of the Ckeditor RichTextField.

Adding Multiple Images

The internet and StackOverflow has a number of answers regarding how to add multiple image field to an object. Most of them suggest two major ways which are as follows

The first method couldn’t be used in the Portal because the Portal uses Crispy Forms to render forms so it becomes difficult to use ajax for the form fields.

The second method was also ruled out because in the project, we use Class Based Views and so could not suddenly change to Function Based Views

And then suddenly comes this angel in disguise. A library which solves both my problems

The Django-MultiUpload Library

This library is a free open source library available on GitHub which helps add multiple file form fields pretty easily. The link for the Docs. Do it out.

So in simple three steps the problem is solved.

  • Add image model to database which has foreign key to a Meetup
class MeetupImages(models.Model):
meetup = models.ForeignKey(Meetup, verbose_name="Meetup")
image = models.FileField(upload_to="meetup/images", verbose_name="Meetup Image")
  • Add the Field to the Form
images = MultiFileField(required=False)
  • Saving the file by overriding the save() method for forms
for img in self.cleaned_data['images']:
MeetupImages.objects.create(image=img, meetup=instance)

And Tada!!. We have the Perfectly working fields.

Happy Reading!!!

--

--