• Register now to get access to thousands of Tutorials, Leaked content, Hot NSFW and much more. Join us as we build and grow the community.

Multiple File Upload in Django Tutorial

chance808

Google Whisperer
C Rep
0
0
0
Rep
0
C Vouches
0
0
0
Vouches
0
Posts
165
Likes
130
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
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. urlpatterns =

    [
  6. path(

    ''

    ,

    views.formpage

    ,

    name=

    'home'

    )

    ,
  7. path(

    'uploadFiles'

    ,

    views.upload

    ,

    name=

    "upload-files"

    )
  8. ]

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. The `urlpatterns` list routes URLs to views. For more information please see:
  3. https://docs.djangoproject.com/en/4.1/topics/http/urls/
  4. Examples:
  5. Function views
  6. 1. Add an import: from my_app import views
  7. 2. Add a URL to urlpatterns: path('', views.home, name='home')
  8. Class-based views
  9. 1. Add an import: from other_app.views import Home
  10. 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
  11. Including another URLconf
  12. 1. Import the include() function: from django.urls import include, path
  13. 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
  14. """
  15. from

    django.contrib

    import

    admin
  16. from

    django.urls

    import

    path,

    include

  17. from

    django.conf

    import

    settings
  18. from

    django.conf

    .urls

    .static

    import

    static

  19. urlpatterns =

    [
  20. path(

    'admin/'

    ,

    admin.site

    .urls

    )

    ,
  21. path(

    ''

    ,

    include(

    "sampleApp.urls"

    )

    )

    ,
  22. ]

    + 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. Generated by 'django-admin startproject' using Django 4.1.3.

  4. For more information on this file, see
  5. https://docs.djangoproject.com/en/4.1/topics/settings/

  6. For the full list of settings and their values, see
  7. https://docs.djangoproject.com/en/4.1/ref/settings/
  8. """

  9. from

    pathlib import

    Path
  10. import

    os

  11. # Build paths inside the project like this: BASE_DIR / 'subdir'.
  12. BASE_DIR =

    Path(

    __file__)

    .resolve

    (

    )

    .parent

    .parent


  13. # Quick-start development settings - unsuitable for production
  14. # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

  15. # SECURITY WARNING: keep the secret key used in production secret!
  16. SECRET_KEY =

    'django-insecure-r!z9-k!(-5dhtm@p!w$o8cgw8q)2brr4h@(-z!+=mf#gb5pi!_'

  17. # SECURITY WARNING: don't run with debug turned on in production!
  18. DEBUG =

    True

  19. ALLOWED_HOSTS =

    [

    ]


  20. # Application definition

  21. INSTALLED_APPS =

    [
  22. 'django.contrib.admin'

    ,
  23. 'django.contrib.auth'

    ,
  24. 'django.contrib.contenttypes'

    ,
  25. 'django.contrib.sessions'

    ,
  26. 'django.contrib.messages'

    ,
  27. 'django.contrib.staticfiles'

    ,
  28. 'sampleApp.apps.SampleappConfig'
  29. ]
  30. MIDDLEWARE =

    [
  31. 'django.middleware.security.SecurityMiddleware'

    ,
  32. 'django.contrib.sessions.middleware.SessionMiddleware'

    ,
  33. 'django.middleware.common.CommonMiddleware'

    ,
  34. 'django.middleware.csrf.CsrfViewMiddleware'

    ,
  35. 'django.contrib.auth.middleware.AuthenticationMiddleware'

    ,
  36. 'django.contrib.messages.middleware.MessageMiddleware'

    ,
  37. 'django.middleware.clickjacking.XFrameOptionsMiddleware'

    ,
  38. ]

  39. ROOT_URLCONF =

    'multiplefilesubmit.urls'

  40. TEMPLATES =

    [
  41. {
  42. 'BACKEND'

    : 'django.template.backends.django.DjangoTemplates'

    ,
  43. 'DIRS'

    : [

    ]

    ,
  44. 'APP_DIRS'

    : True

    ,
  45. 'OPTIONS'

    : {
  46. 'context_processors'

    : [
  47. 'django.template.context_processors.debug'

    ,
  48. 'django.template.context_processors.request'

    ,
  49. 'django.contrib.auth.context_processors.auth'

    ,
  50. 'django.contrib.messages.context_processors.messages'

    ,
  51. ]

    ,
  52. }

    ,
  53. }

    ,
  54. ]

  55. WSGI_APPLICATION =

    'multiplefilesubmit.wsgi.application'


  56. # Database
  57. # https://docs.djangoproject.com/en/4.1/ref/settings/#databases

  58. DATABASES =

    {
  59. 'default'

    : {
  60. 'ENGINE'

    : 'django.db.backends.sqlite3'

    ,
  61. 'NAME'

    : BASE_DIR / 'db.sqlite3'

    ,
  62. }
  63. }


  64. # Password validation
  65. # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

  66. AUTH_PASSWORD_VALIDATORS =

    [
  67. {
  68. 'NAME'

    : 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'

    ,
  69. }

    ,
  70. {
  71. 'NAME'

    : 'django.contrib.auth.password_validation.MinimumLengthValidator'

    ,
  72. }

    ,
  73. {
  74. 'NAME'

    : 'django.contrib.auth.password_validation.CommonPasswordValidator'

    ,
  75. }

    ,
  76. {
  77. 'NAME'

    : 'django.contrib.auth.password_validation.NumericPasswordValidator'

    ,
  78. }

    ,
  79. ]


  80. # Internationalization
  81. # https://docs.djangoproject.com/en/4.1/topics/i18n/

  82. LANGUAGE_CODE =

    'en-us'

  83. TIME_ZONE =

    'Asia/Manila'

  84. USE_I18N =

    True

  85. USE_TZ =

    True


  86. # Static files (CSS, JavaScript, Images)
  87. # https://docs.djangoproject.com/en/4.1/howto/static-files/

  88. STATIC_URL =

    '/static/'
  89. STATICFILES_DIRS =

    (
  90. # location of your application, should not be public web accessible
  91. './static'

    ,
  92. )
  93. MEDIA_URL =

    "/media/"
  94. MEDIA_ROOT =

    os

    .path

    .join

    (

    BASE_DIR,

    'media'

    )
  95. # Default primary key field type
  96. # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

  97. DEFAULT_AUTO_FIELD =

    'django.db.models.BigAutoField'


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. # Create your models here.

  3. class

    FileList(

    models.Model

    )

    :
  4. 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. # Upload File Form
  6. class

    UploadFiles(

    forms.ModelForm

    )

    :
  7. file_path =

    forms.FileField

    (

    label=

    "Select Multiple File"

    ,

    help_text=

    "The Avatar field is required."

    ,

    widget =

    forms.FileInput

    (

    attrs=

    {

    'multiple'

    :'multiple'

    ,

    'class'

    :'file-input'

    }

    )

    )
  8. class

    Meta:
  9. model =

    FileList
  10. 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. <head

    >
  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. <body

    >


  13. <main class

    =

    "my-5"

    >
  14. {% if messages %}
  15. {% for message in messages %}
  16. <div

    class

    =

    "alert alert-{{message.tags}}"

    >

    {{ message }}</

    div

    >
  17. {% endfor %}
  18. {% endif %}
  19. {% block pageContent %} {% endblock pageContent %}
  20. </

    main>
  21. {% block ScriptBlock %} {% endblock ScriptBlock %}
  22. </

    body

    >

  23. </

    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. # Create your views here.

  7. def

    test

    (

    request)

    :
  8. return

    HttpResponse(

    '<h1>Hello World!</h1>'

    )

  9. def

    formpage(

    request)

    :
  10. form =

    UploadFiles(

    )
  11. print

    (

    form.fields

    )
  12. return

    render(

    request,

    "sampleform.html"

    ,

    {

    "form"

    : form}

    )

  13. def

    upload(

    request)

    :
  14. if

    request.method

    ==

    'POST'

    :
  15. form =

    UploadFiles(

    request.POST

    ,

    request.FILES

    )
  16. if

    form.is_valid

    (

    )

    :
  17. files =

    [

    ]
  18. if

    'file_path'

    in

    request.FILES

    :
  19. for

    file

    in

    request.FILES

    .getlist

    (

    'file_path'

    )

    :
  20. files.append

    (

    FileList(

    file_path=

    file

    )

    )
  21. # print(len(files))
  22. if

    len

    (

    files)

    >

    0

    :
  23. try

    :
  24. FileList.objects

    .bulk_create

    (

    files)
  25. messages.success

    (

    request,

    "File(s) has been uploaded successfully."

    )
  26. except

    Exception

    as

    ex:
  27. messages.error

    (

    request,

    ex)
  28. else

    :
  29. messages.error

    (

    request,

    'Form data is invalid'

    )

  30. 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. # Register your models here.
  4. 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

Success Message

Admin Site

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 =)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

Create an account or login to comment

You must be a member in order to leave a comment

Create account

Create an account on our community. It's easy!

Log in

Already have an account? Log in here.

452,513

356,536

356,561

Top
Raidforums