How to Upload Multiple Images in Django

Cover image for Upload multiple images simultaneously in your Django app using Dropzone Js

Nick Langat

Upload multiple images simultaneously in your Django app using Dropzone Js

Hello guys information technology'due south been a infinitesimal! I was on a small-scale pause simply at present am back and in this tutorial we are going to acquire how we can upload multiple images to a Django back end. By default the Django beliefs is that you select a unmarried image and upload it to the server so echo which begs the question isn't that a time consuming and tedious process, say if we have chiliad images? It is.
Fortunately, at that place is a tool that can aid us go around this problem, a JavaScript library called Dropzone . Let's not waste more seconds, let's get into information technology!

Project SETUP

Permit's speedily navigate to our desktop directory and bootstrap the back cease.

            cd ~/Desktop  mkdir django_dropzone && cd django_dropzone  virtualenv env  source env/bin/activate  pip install django  django-admin startproject mysite .  python manage.py startapp cadre                      

Enter fullscreen way Exit fullscreen mode

Next add together core to the list of installed apps in settings.py.
While there also update the templates section equally follows:

                          import              os              'DIRS'              :              [              os              .              path              .              bring together              (              BASE_DIR              ,              'templates'              )],                      

Enter fullscreen way Get out fullscreen fashion

Then as well update the static settings like and then:

                          STATIC_URL              =              '/static/'              if              DEBUG              :              STATICFILES_DIRS              =              [              bone              .              path              .              join              (              BASE_DIR              ,              'static'              )]              else              :              STATIC_ROOT              =              os              .              path              .              join              (              BASE_DIR              ,              'static'              )              MEDIA_ROOT              =              os              .              path              .              join              (              BASE_DIR              ,              'media'              )              MEDIA_URL              =              '/media/'                      

Enter fullscreen mode Exit fullscreen mode

Paradigm MODEL

We have set up our settings.py and it's good to become. Motility to core/models.py and add the post-obit code:

                          from              django.db              import              models              # Create your models here.                            class              Image              (              models              .              Model              ):              image              =              models              .              ImageField              (              upload_to              =              'images/'              )              date              =              models              .              DateTimeField              (              auto_now_add              =              True              )              course              Meta              :              ordering              =              [              '-date'              ]              def              __str__              (              cocky              ):              return              str              (              self              .              date              )                      

Enter fullscreen mode Exit fullscreen mode

Go ahead and makemigrations and so migrate to apply the changes to the db.
Side by side we go the the views.py. Write the following lawmaking to information technology.

                          from              django.shortcuts              import              render              from              django.http              import              HttpResponse              ,              JsonResponse              from              .models              import              Epitome              # Create your views here.                            def              home              (              request              ):              images              =              Image              .              objects              .              all              ()              context              =              {              'images'              :              images              }              render              render              (              request              ,              'index.html'              ,              context              )              def              file_upload              (              request              ):              if              asking              .              method              ==              'Post'              :              my_file              =              request              .              FILES              .              get              (              'file'              )              Epitome              .              objects              .              create              (              epitome              =              my_file              )              return              HttpResponse              (              ''              )              render              JsonResponse              ({              'mail service'              :              'fasle'              })                      

Enter fullscreen mode Exit fullscreen mode

Adjacent create core/urls.py and add the following lawmaking to it:

                          from              django.urls              import              path              from              .              import              views              urlpatterns              =              [              path              (              ''              ,              views              .              abode              ,              name              =              'home'              ),              path              (              'upload/'              ,              views              .              file_upload              ),              ]                      

Enter fullscreen mode Leave fullscreen manner

To finalise the Python part, add the post-obit code to the project'southward urls.py

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

Enter fullscreen mode Go out fullscreen mode

DROPZONE SETUP

We are done with the logic let's do the UI stuff. Create a binder called static and in it create 2 files:

            touch static/main.js  touch static/way.css                      

Enter fullscreen mode Leave fullscreen mode

Add the following code to main.js:

                          Dropzone              .              autoDiscover              =              fake              ;              const              myDropzone              =              new              Dropzone              (              '              #my-dropzone              '              ,{              url              :              '              upload/              '              ,              maxFiles              :              5              ,              maxFilesize              :              ii              ,              acceptedFiles              :              '              .jpg              '              ,              })                      

Enter fullscreen mode Exit fullscreen mode

And the following to style.css:

                          body              {              background              -              colour              :              #              f8f8f8              !              important              ;              }              .              dz              {              border              :              dashed              !              of import              ;              groundwork              -              color              :              #              ccc              !              important              ;              border              -              radius              :              ten              px              !              important              ;              }              .              dz              :              hover              {              background              -              color              :              aliceblue              !              important              ;              }                      

Enter fullscreen fashion Go out fullscreen mode

Next create a binder called templates and in it create two files:

            touch templates/base.html  touch templates/index.html                      

Enter fullscreen mode Exit fullscreen mode

Add the following code to base of operations.html

                          {              %              load              static              %              }              <!              doctype              html              >              <              html              lang              =              "              en              "              >              <              head              >              <!--              Required              meta              tags              -->              <              meta              charset              =              "              utf-eight              "              >              <              meta              proper name              =              "              viewport              "              content              =              "              width=device-width, initial-scale=1, shrink-to-fit=no              "              >              <!--              Bootstrap              CSS              -->              <              link              rel              =              "              stylesheet              "              href              =              "              https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css              "              >              <!--              Font              awesome              -->              <              link              rel              =              "              stylesheet              "              href              =              "              https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.vii.0/css/font-awesome.min.css              "              >              <!--              custom              css              &              js              -->              <              link              rel              =              "              stylesheet              "              href              =              "              {% static 'style.css' %}              "              >              <              script              src              =              "              {% static 'main.js' %}              "              defer              ><              /script              >                            <              script              src              =              "              https://rawgit.com/enyo/dropzone/chief/dist/dropzone.js              "              ><              /script              >                            <              link              rel              =              "              stylesheet              "              href              =              "              https://rawgit.com/enyo/dropzone/master/dist/dropzone.css              "              >              <              title              >              Drag              and              Drop              Django              |              {              %              cake              title              %              }{              %              endblock              title              %              }              <              /championship              >                            <              /head              >                            <              torso              >              <              div              class              =              "              container mt-3              "              >              {              %              block              content              %              }              {              %              endblock              content              %              }              <              /div              >                            <!--              Optional              JavaScript              -->              <!--              jQuery              beginning              ,              then              Popper              .              js              ,              then              Bootstrap              JS              -->              <              script              src              =              "              https://code.jquery.com/jquery-iii.5.1.min.js              "              ><              /script              >                            <              script              src              =              "              https://cdn.jsdelivr.internet/npm/popper.js@i.xvi.1/dist/umd/popper.min.js              "              ><              /script              >                            <              script              src              =              "              https://stackpath.bootstrapcdn.com/bootstrap/4.5.ii/js/bootstrap.min.js              "              ><              /script              >                            <              /body              >                            <              /html              >                                    

Enter fullscreen fashion Exit fullscreen mode

And the following to index.html:

                          {              %              extends              '              base of operations.html              '              %              }              {              %              block              content              %              }              <              h6              >              UPLOAD              MULTIPLE              IMAGES              Now              <              /h6              >                            <              br              >              <              form              enctype              =              '              multipart/class-information              '              action              =              "              upload/              "              method              =              '              POST              '              course              =              "              dropzone dz              "              id              =              "              my-dropzone              "              >              {              %              csrf_token              %              }              <              div              class              =              "              fallback              "              >              <              input              name              =              "              file              "              blazon              =              "              file              "              multiple              />              <              /div              >                            <              /form              >                            {              %              endblock              %              }                      

Enter fullscreen way Exit fullscreen mode

SPIN UP THE SERVER

At present get to the terminal and:

            python manage.py runserver                      

Enter fullscreen way Go out fullscreen mode

Cheque the browser and upload images, be sure to select multiple.

1
and
2

MISSION SUCCESS

Yeah that should do it for this commodity. Thanks for keeping me company and coding along. You tin can take hold of the source code of this project hither
Y'all can connect with me on LinkedIn and on Twitter
Cheers and see you next fourth dimension!

jonesbutamene.blogspot.com

Source: https://dev.to/nick_langat/upload-multiple-images-simultaneously-in-your-django-app-using-dropzone-js-11pi

0 Response to "How to Upload Multiple Images in Django"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel