How to Upload Multiple Files in Django?

Hi Dev,
This tutorial shows you django multiple file upload example. you can see django multiple files upload. This tutorial will give you simple example of multiple file upload django. you will learn django multiple file upload with preview. follow bellow step for how to multiple upload pdf in django.
Here, we will install django and create a simple form with a file input field that you can use to select multiple files. after submitting the form we will store those files in a folder and database.
Django framework the file data is store into request.FILES. you need a FileField form that a view will handle this form and this form will receive file data in request.FILES which is a dictionary containing a key for each FileField. So let’s say if your form has an input field with name file and form has an attribute enctype="multipart/form-data", then file data can be accessible as request.FILES['file']. If your form does not have attribute enctype="multipart/form-data" then request.FILES['file'] will be empty.
Here i explained simply step by step example of django multiple file upload example in database.
Step 1: Create a ProjectIn this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject exampleStep 2: Create a App
Now we'll create a single app called core to store a list of files name. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.
python3 manage.py startapp coreStep 3: Update setting.py
In this step we require to do two things in our settings.py file.one is register our new app in INSTALLED_APPS within our settings.py second is to configure our media folder. Add the below lines to your settings.py file:
Next, you need to add it in the settings.py file as follows:
settings.pyimport os .... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ] .... MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/"Step 4: Create a Model
In this step we will require the database model for storing contacts.Open the core/models.py file and add the following code:
core/models.pyfrom django.db import models class Document(models.Model): file = models.FileField(upload_to="documents/%Y/%m/%d")
Next, you need to migrate your database using the following command:
python manage.py makemigrations python manage.py migrateStep 5: Create a Form
In this step We need to create a form that will be used .like add a bootstrap class and validation etc.. plus we need to add custom styling.
core/forms.pyfrom django import forms from .models import * from django.utils.translation import gettext as _ class DocumentForm(forms.ModelForm): file = forms.FileField(label=_('Choose File'), required=True, error_messages = {'required':'The file field is required.','invalid':_("Files only")}, widget=forms.FileInput(attrs={'multiple':True, 'class': 'form-control custom-file-input','id' : 'customFile'}) ) class Meta: model = Document fields = ['file',]Step 6: Creating the Views
In this step, we need to configure our views. The file_upload page will just be a template and store to multiple image database and our media folder.So, open the core/views.py file and add:
core/views.pyfrom django.shortcuts import render from .forms import * from .models import * from django.contrib import messages import os # Create your views here. def file_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) files = request.FILES.getlist('file') if form.is_valid(): for file in files: ext = os.path.splitext(file.name)[1] valid_extensions = ['.pdf', '.csv', '.doc', '.docx', '.xlsx', '.xlx'] if ext.lower() in valid_extensions: Document.objects.create(file=file) if ext.lower() in valid_extensions: messages.success(request, 'File Upload Successfully') else: messages.error(request, 'Unsupported file extension!') else: form = DocumentForm() return render(request, 'index.html', {'form' : form})Step 7: Creating the Template
Next, open the core/templates/index.html file and the add:
core/templates/index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tuts-Station.com</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <style type="text/css"> body{ background-color: #f7fcff; } </style> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-8"> {% if messages %} <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} <div class="card"> <div class="card-header"> <h4>How to Multiple File Upload in Django? - <span class="text-primary">Tuts-Station.com</span></h4> </div> <div class="card-body"> <form method = "post" enctype="multipart/form-data" novalidate> {% csrf_token %} <label>File:</label> <div class="custom-file"> {% for field in form %} <label class="custom-file-label" for="customFile">{{ field.label }}</label> {{ field }} <small class="text-danger mt-2">{{ field.errors|striptags }}</small> {% endfor %} </div> <small class="mt-2">(File extension must be pdf, csv, doc, docx, xlsx, xlx format.)</small> <div class="row mt-4"> <div class="col-lg-12 text-center"> <button class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> /*------------------------------------------ -------------------------------------------- Custom File Input -------------------------------------------- --------------------------------------------*/ $(".custom-file-input").on("change", function() { var fileName = $(this).val().split("\\").pop(); $(this).siblings(".custom-file-label").addClass("selected").html(fileName); }); </script> </html>Step 8: Creating Urls
In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code:
core/urls.pyfrom django.urls import path from . import views urlpatterns = [ path('files/', views.file_upload, name="file_upload"), ]
Next, we require to add a URL path for our example project which can be done by importing include and setting a path for it.
example/urls.pyfrom django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include('core.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)Run the Server
In this step, we’ll run the local development server for playing with our app without deploying it to the web.
python manage.py runserver
Next, go to the http://localhost:8000/files address with a web browser.
I Hope It will help you....