Multiple File Upload in Django Tutorial

In this tutorial, you can learn to Iterate Request Files and Upload Multiple Files at once using Django in Python. This tutorial aims to provide students and beginners with a reference for learning to develop a dynamic website using Django. Here, I will be giving some steps for creating a simple web application that results in an App that allows users to upload multiple files at once.

Getting Started

Before we start the coding part, please download and install Python and Django on your local machine first.

Creating a Simple Django Project

Create a Django Project

Open your terminal or command prompt and run the following:

django-admin startproject multiplefilesubmit

The provided script provided above creates a new Django project which creates a new source code folder on the current directory. The project directory contains the default files of a Django Project.

Creating an App

Next, execute the following script on your terminal or command prompt. It will create the app in your Django Project containing the default files for the Django App.

python manage.py startapp sampleApp

Creating the App Routing File

Next on the sampleApp directory, create a new python file named urls.py. The file contains the Python scripts that help the Django Application routes.

  1. from django.contrib import admin
  2. from django.contrib.auth import views as auth_views
  3. from django.urls import path
  4. from . import views
  5.  
  6. urlpatterns = [
  7. path('', views.formpage, name='home'),
  8. path('uploadFiles', views.upload, name="upload-files")
  9. ]

Creating the Project Routing File

After we created the Application routing file, we need to update the project routing files. Update the multiplefilesubmit >> urls.py.

  1. """multiplefilesubmit URL Configuration
  2.  
  3. The `urlpatterns` list routes URLs to views. For more information please see:
  4. https://docs.djangoproject.com/en/4.1/topics/http/urls/
  5. Examples:
  6. Function views
  7. 1. Add an import: from my_app import views
  8. 2. Add a URL to urlpatterns: path('', views.home, name='home')
  9. Class-based views
  10. 1. Add an import: from other_app.views import Home
  11. 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
  12. Including another URLconf
  13. 1. Import the include() function: from django.urls import include, path
  14. 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
  15. """
  16. from django.contrib import admin
  17. from django.urls import path, include
  18.  
  19. from django.conf import settings
  20. from django.conf.urls.static import static
  21.  
  22. urlpatterns = [
  23. path('admin/', admin.site.urls),
  24. path('', include("sampleApp.urls")),
  25. ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Update Settings

Next, open the multiplefilesubmit >> settings.py file and update the script like the following.

  1. """
  2. Django settings for multiplefilesubmit project.
  3.  
  4. Generated by 'django-admin startproject' using Django 4.1.3.
  5.  
  6. For more information on this file, see
  7. https://docs.djangoproject.com/en/4.1/topics/settings/
  8.  
  9. For the full list of settings and their values, see
  10. https://docs.djangoproject.com/en/4.1/ref/settings/
  11. """
  12.  
  13. from pathlib import Path
  14. import os
  15.  
  16. # Build paths inside the project like this: BASE_DIR / 'subdir'.
  17. BASE_DIR = Path(__file__).resolve().parent.parent
  18.  
  19.  
  20. # Quick-start development settings - unsuitable for production
  21. # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
  22.  
  23. # SECURITY WARNING: keep the secret key used in production secret!
  24. SECRET_KEY = 'django-insecure-r!z9-k!(-5dhtm@p!w$o8cgw8q)2brr4h@(-z!+=mf#gb5pi!_'
  25.  
  26. # SECURITY WARNING: don't run with debug turned on in production!
  27. DEBUG = True
  28.  
  29. ALLOWED_HOSTS = []
  30.  
  31.  
  32. # Application definition
  33.  
  34. INSTALLED_APPS = [
  35. 'django.contrib.admin',
  36. 'django.contrib.auth',
  37. 'django.contrib.contenttypes',
  38. 'django.contrib.sessions',
  39. 'django.contrib.messages',
  40. 'django.contrib.staticfiles',
  41. 'sampleApp.apps.SampleappConfig'
  42. ]
  43. MIDDLEWARE = [
  44. 'django.middleware.security.SecurityMiddleware',
  45. 'django.contrib.sessions.middleware.SessionMiddleware',
  46. 'django.middleware.common.CommonMiddleware',
  47. 'django.middleware.csrf.CsrfViewMiddleware',
  48. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  49. 'django.contrib.messages.middleware.MessageMiddleware',
  50. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  51. ]
  52.  
  53. ROOT_URLCONF = 'multiplefilesubmit.urls'
  54.  
  55. TEMPLATES = [
  56. {
  57. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  58. 'DIRS': [],
  59. 'APP_DIRS': True,
  60. 'OPTIONS': {
  61. 'context_processors': [
  62. 'django.template.context_processors.debug',
  63. 'django.template.context_processors.request',
  64. 'django.contrib.auth.context_processors.auth',
  65. 'django.contrib.messages.context_processors.messages',
  66. ],
  67. },
  68. },
  69. ]
  70.  
  71. WSGI_APPLICATION = 'multiplefilesubmit.wsgi.application'
  72.  
  73.  
  74. # Database
  75. # https://docs.djangoproject.com/en/4.1/ref/settings/#databases
  76.  
  77. DATABASES = {
  78. 'default': {
  79. 'ENGINE': 'django.db.backends.sqlite3',
  80. 'NAME': BASE_DIR / 'db.sqlite3',
  81. }
  82. }
  83.  
  84.  
  85. # Password validation
  86. # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
  87.  
  88. AUTH_PASSWORD_VALIDATORS = [
  89. {
  90. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  91. },
  92. {
  93. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  94. },
  95. {
  96. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  97. },
  98. {
  99. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  100. },
  101. ]
  102.  
  103.  
  104. # Internationalization
  105. # https://docs.djangoproject.com/en/4.1/topics/i18n/
  106.  
  107. LANGUAGE_CODE = 'en-us'
  108.  
  109. TIME_ZONE = 'Asia/Manila'
  110.  
  111. USE_I18N = True
  112.  
  113. USE_TZ = True
  114.  
  115.  
  116. # Static files (CSS, JavaScript, Images)
  117. # https://docs.djangoproject.com/en/4.1/howto/static-files/
  118.  
  119. STATIC_URL = '/static/'
  120. STATICFILES_DIRS = (
  121. # location of your application, should not be public web accessible
  122. './static',
  123. )
  124. MEDIA_URL = "/media/"
  125. MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  126. # Default primary key field type
  127. # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
  128.  
  129. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  130.  

Update Application Model

Open your sampleApp >> models.py file to create the database table for storing the file paths.

  1. from django.db import models
  2.  
  3. # Create your models here.
  4.  
  5. class FileList(models.Model):
  6. file_path = models.FileField(blank=True,null = True, upload_to='fileuploads/')

Migrations

Next, make migrations to execute the model changes on the database and run the migration. Execute the following script in your terminal or command prompt.

python manage.py makemigrations

python manage.py migrate

Creating the Form

On your sampleApp directory, create a new Python file named forms.py. The file contains the model forms scripts.

  1. # Import forms of Django
  2. from django import forms
  3. # Import FileList Model
  4. from sampleApp.models import FileList
  5.  
  6. # Upload File Form
  7. class UploadFiles(forms.ModelForm):
  8. file_path = forms.FileField(label="Select Multiple File", help_text="The Avatar field is required.", widget = forms.FileInput(attrs={'multiple':'multiple', 'class':'file-input'}))
  9. class Meta:
  10. model = FileList
  11. fields = ('file_path',)

Creating the Base Template

Next, create a new directory inside the sampleApp folder named templates. Then inside the created folder, create files for the following HTML files. Save the files according to the filename I provided above each file.

base.html

  1. {% load static %}
  2. <!DOCTYPE html>
  3. <html lang="en">
  4.  
  5. <meta charset="UTF-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Multiple File Upload</title>
  9. <link rel="stylesheet" href="{% static 'styles.css' %}">
  10. {% block headerContent %} {% endblock headerContent %}
  11. </head>
  12.  
  13.  
  14.  
  15. <main class="my-5">
  16. {% if messages %}
  17. {% for message in messages %}
  18. <div class="alert alert-{{message.tags}}">{{ message }}</div>
  19. {% endfor %}
  20. {% endif %}
  21. {% block pageContent %} {% endblock pageContent %}
  22. </main>
  23. {% block ScriptBlock %} {% endblock ScriptBlock %}
  24. </body>
  25.  
  26. </html>

sampleform.html

  1. {% extends 'base.html' %}
  2. {% block pageContent %}
  3. <div id="wrapper">
  4. <form action="/uploadFiles" method="POST" enctype="multipart/form-data">
  5. {% csrf_token %}
  6. {% for field in form %}
  7. <div class="form-group">
  8. {{ field.label_tag }}
  9. {{ field }}
  10. </div>
  11. {% endfor %}
  12. <div class="form-btn">
  13. <button id="form-submit">Upload File(s)</button>
  14. </div>
  15. </form>
  16. </div>
  17. {% endblock pageContent %}

Update the View File

On your sampleApp directory, open the views.py file on your text editor and update the scripts like the following. It contains the Python script for rendering the form page and uploading the files to the database.

  1. from django.shortcuts import render, redirect
  2. from django.http import HttpResponse
  3. from django.contrib import messages
  4. from .models import FileList
  5. from .forms import UploadFiles
  6.  
  7. # Create your views here.
  8.  
  9. def test(request):
  10. return HttpResponse('<h1>Hello World!</h1>')
  11.  
  12. def formpage(request):
  13. form = UploadFiles()
  14. print(form.fields)
  15. return render(request, "sampleform.html", {"form": form})
  16.  
  17. def upload(request):
  18. if request.method == 'POST':
  19. form = UploadFiles(request.POST, request.FILES)
  20. if form.is_valid():
  21. files = []
  22. if 'file_path' in request.FILES:
  23. for file in request.FILES.getlist('file_path'):
  24. files.append(FileList(file_path=file))
  25. # print(len(files))
  26. if len(files) > 0:
  27. try:
  28. FileList.objects.bulk_create(files)
  29. messages.success(request, "File(s) has been uploaded successfully.")
  30. except Exception as ex:
  31. messages.error(request, ex)
  32. else:
  33. messages.error(request, 'Form data is invalid')
  34.  
  35. return redirect('home')

Register Model to Admin Site

Next, register the FileList to the admin site so we can manage the uploaded file paths on the admin site. Open the sampleApp >> admin.py.

  1. from django.contrib import admin
  2. from sampleApp.models import FileList
  3.  
  4.  
  5. # Register your models here.
  6. admin.site.register(FileList)

Creating a Super User Account

To create a super user account, run the following script on your terminal or command prompt.

python manage.py createsuperuser

Run the Application

Execute the following script on your terminal and command prompt to run the application.

python manage.py runserver

Then, browse the application using your preferred browser. The application link will be provided upon executing the runserver script i.e. http://127.0.0.1:8000/ and http://127.0.0.1:8000/admin for the admin site.

Snapshots

Here are some snapshots of the overall result of the project application.

Page UI

Multiple File Upload in Django Tutorial

Success Message

Multiple File Upload in Django Tutorial

Admin Site

Multiple File Upload in Django Tutorial

There you go! I have also provided the complete source code that I created on this website and it is free to download. The download button can be found below this tutorial's content. Feel free to download and modify the source code the way you wanted to enhance your programming capabilities.

That's it! I hope this Multiple File Upload in Django Tutorial will help you with what you are looking for and that you'll find this useful for your current and future Django Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Comments

Add new comment