Python Django – Multiple Files Validation and Uploads

In this post, we’ll learn Python Django – Multiple Files Validation and Uploads.

Table Of Contents

Introduction

In this post, we’ll learn to upload files to the server without using form class. We understand that forms in Django have a lot of importance in retrieving and validating data.

Create View

In views.py we have created a function manually_file_upload_view(request) this will render us HTML form were we submit the file for upload.

    from django.shortcuts import render,redirect
    from django.http import HttpResponse,HttpResponseRedirect
    from django.urls import reverse
    from django.conf import settings
    import os
    def manually_file_upload_view(request):
        context={}
        return render(request,'forms/manually_file_upload_form.html',context)

Here the render() method to display form in browser. The function render takes three arguments and they are request object, template_path and context which is data passed to the template.

Create an HTML Form

To render template create a template file in the directory templates/forms/manually_file_upload_form.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Django File Upload</title>
</head>
<body>
    <form action="{% url 'forms:manually-file-upload-save' %}" method="post" enctype="multipart/form-data"  >
        {% csrf_token %}
        <label for="">Upload File</label><br>
        <input type="file" name="file_upload" multiple>
        <br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

The Form is submitted to route {% url 'forms:manually-file-upload-save' %} and these routes are declared in urls.py the file in the app.

path('manually-file-upload-save', views.manually_file_upload_save, name='manually-file-upload-save'),

Caution

You will receive an exception if you don’t specify the above route.

Submit Form and Save Files into Directory

This is a final step where the form data gets submitted to and the files are fetched and uploaded into the specified directory.

Note

Specifying {% csrf_token %} the template tag is mandatory while submitted form as it prevents your application from Cross-Site request forgery attacks.

In views.py.

def manually_file_upload_save(request):
    file_list = []
    if request.method == 'POST':
        if request.FILES.get("file_upload") is not None:
            file_list = request.FILES.getlist("file_upload")
        result = file_upload_interface(request, file_list, allowed_mime_types=["png"])
        return HttpResponse("Uploaded Files 
 {}".format(result.get("files")))
        

#This function uploads multiple files and returns the name of file
def file_upload_interface(request, file_list, dir_path = "uploads/", allowed_mime_types=[]):
    if not isinstance(file_list, list):
        file_list=list(file_list)
    directory = os.path.join(settings.BASE_DIR, dir_path)
    info={
        "files" : []
    }
    for file in file_list:
        file_name= file._name
        file_mime = file.content_type.split('/')[1]
        path= "{}{}".format(directory, file_name)

        is_allowed_to_upload=False
        #check allowed mime types if that file does not belong to mime type remove it
        if len(allowed_mime_types) > 0:
            if file_mime in  allowed_mime_types:
                is_allowed_to_upload=True
        else:
            is_allowed_to_upload=True

        if is_allowed_to_upload is True:
            with open(path, 'wb+') as destination:
                for chunk in file.chunks():
                    destination.write(chunk)
                info["files"].append(file_name)
    return info

When the form has submitted the function manually_file_upload_save() is called. To retrieve the uploaded files from request object through request.FILES.get(“”)  and to retrieve multiple uploaded files as list use request.FILES.getlist(“”).

You have to then pass these list as file_list to the function file_upload_interface(). This function will loop over multiple file object and push the file into a specified directory.

Validate File Type Extensions for Upload

To allow a particular extension of files to be uploaded pass a list of allowed_mime_types=["png"] to function file_upload_interface. The variable is_allowed_to_upload is used as a flag to allow or disallow file from uploading.

Opening file using with the statement allows consistency in connection with the files. The file is uploaded to its destination directory via destination.write(chunk) a method.

Video Preview

Note

Visit Django Documentation File Uploads for more information.

Conclusion

In conclusion, We have come to the end of our post on Python Django – Multiple Files Validation and Uploads. If you have any doubts kindly mention in the comments section and we’ll reach you soon.

Related Posts

Summary
Review Date
Reviewed Item
Python Django - Multiple Files Validation and Uploads
Author Rating
51star
1star1star1star1star
Software Name
Django Web Framework
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development