How to upload a file with a progress bar using Django and Javascript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys in this one we are going to do a image upload with a progress bar so let me show you exactly what we are going to create i'm going to select the file let's choose this yoga we see a progress bar and here is the image that we successfully uploaded to the database let's select another one this is reset it i'm going to click cancel oops something went wrong after two seconds we have a blank form so let's try to upload this amusement park picture and there it is so yeah without further ado let's get started all right guys so before we actually take a look at what have i done so far i would like to apologize for the delay in video releases so i know that some of you are waiting for for example the fifth part of the crypto real time application uh some of you are waiting for um the first part of the friendly introduction to django i'm really sorry about this i had some health issues so i can only give you an advice that if you are working seven days a week 10 12 maybe even more hours per day it won't be a bad idea to you know just slow down a little bit so this is exactly what happened to me i had some health issues but everything is okay right now and i'm ready to proceed and with that being said let's take a look at what have i done so far so i started a brand new project called upload broach and i added one app called uploads this uploads app has been added to the installed apps list and over here i also told django where to look for additional templates i created a templates directory over here according to those settings over here and i placed base html i also provided some settings for the static and media files i also created in our base directory um the static folder where we have a favorite icon main js and style css as well as the media folder and this media folder will be updated every time a user sends an image to our database and as the next step let's take a look at the urls py over here we have included the settings for the static and media files in the url patterns and we also have one path as the home view so we will take a look at this in just a second and this is the urls py file which is placed in the main project folder okay so as the next file let's take a look at base html and this is a modified version of the template that i got from getbootstrap.com so we have the bootstrap css i also placed a favorite icon and here we have jquery and custom css and js so here we are referring to the files in our static directory and at the top i've loaded static and then we have only one block defined as content and yeah once we inherit from the space html this is the place where we will focus on at least on the html part and the javascript part will be done of course in the main.js so let's take a look at now the views py here we have just an ordinary home view which is which was registered in the urls py in our main project folder and um we have our main html so for now we only see hello world then we have main.js and over here we should see in the console um hello world as well and then we have style css which is empty file for now so um okay as you can see i also created a super user i'm already logged in into django administration and here i have hello world and hello world in the console in the developer tool so you might want to go right click inspect and then choose the console okay so right now we can actually begin coding so let's jump into our uploads application let's find models py file and over here let's define a new class called upload which inherits from models dot model and we will have only one field over here i'm going to call it image and this is going to be a models image field so make sure to install pillow so you need to run in the console pip install pillow and this will do the trick so over here i'm going to specify the upload to to be images okay so inside the media directory we will have another one called images and this is where all the images will be stored and then let's return a string representation and let's return str self pk alright so i'm going to save this i'm going to register this model in our admin so we need to go to uploads admin and here from dot models we want to import the upload and then at the bottom admin site register upload okay i'm going to save this and what else i'm going to do i'm also going to create a forms py file and here let's create an upload form so from django import forms and we also need our model because we will be using a modal form so from dot models let's import our upload and let's define a new class upload form which is going to be forms dot model form it inherits from forms dot model form and here with the class meta i'm going to indicate that the model is upload and the fields are going to be image all right so um let's also not forget to run the migration so i'm going to quit the server from running python manage py make migrations and python manage py migrate okay perfect um so right now i'm just going to also run the server and actually we can right now go to our views so in the views py we are going to bring in our form so from dot models oh sorry from dot forms we want to import our upload form and over here i'm going to define a form as upload form with request post or none and request files or none all right so we have our form let's pass it in to the template so we have uploads main html this is this particular file over here in our uploads application in the templates directory in in the templates directory we have an uploads directory and over there we have this main html and here we are passing the context which is this dictionary and in this moment it is empty so let's put in form and over here form okay so now i'm going to save this and we can jump in to the main html over here for now we have only hello world so let's actually delete it and yeah maybe let's begin from the form itself so i'm going to create a form with an id upload form i'm going to close it off i'm going to put in a csrf token and put in form s p we don't need any uh submit button or stuff like that so this is the first step we have a upload form of a csrf token and this is the form that we created in the forms py file so maybe at the top of the form let's create some boxes so the first one is going to be a div with an id alert box and here we will see a confirmation that we successfully uploaded a certain image or um we actually failed to do so so this is going to be a div with id alert box and let's close it off and below let's have a image box so i'm going to define the id as image box and here we will display the image that we successfully downloaded the uploaded sorry okay so we have an alert box and an image box let's add a break line between the image box and the form and then afterwards after the form let's add another break line and here we will have another div with the id of progress box so this is the place where we will see our progress bar and maybe also let's add a class not visible so this is the class that we actually need to create so let's go to the style css immediately not visible and here we just need to put in display none okay and i'm going to save this and return to the main html and here i'm going to close up the div and let's also have another div with the button for canceling to upload okay so i'm going to call it cancel box and also i'm going to provide a class equal to not visible so at the beginning it will be not visible we will change this to visible when we will actually remove this class making it visible once the file is uploaded so let's put it like this and inside let's create a button with a class is equal to btn btn danger so it will be a red button cancel let's close off the button and let's give it some kind of a id maybe let's call it cancel btn all right so let's save this and yeah i think we are done over here for the block content um at least for now so let's actually grab those other elements we need an alert box an image box upload form progress box cancel box cancel btn we we need all of those things and this is what we are going to do in main.js so here we have uh hello world i'm going to leave it and below i'm going to begin from the upload form so i'm going to put in a const equal to upload form and this is we're going to be document get element by id and let's put in upload form let's console log the upload form and let's see how this actually changed so here we have an image we have our form and here we have our form displayed in the console all right let's continue then so maybe as the next step let's take a look at the input itself so i'm going to open it up and here we have an input type hidden with a csrf middleware token and then we have a paragraph and here we have an input type file name image and here we have the id and this is extremely important because we will add a event listener on this particular input so we can grab it by this id image and let's do it so i'm going to maybe over here create a const and i'm going to call it input and this is going to be again document get element by id input sorry not input the name was the id was id image id image and over here i want to console log the input right now so i'm going to save this refresh and here is our input okay so yeah everything is working we can actually continue i'm going to also create a const for the alert box and this is going to be document get element by id alert box then what we had we had an image box const image box and this is going to be document get element by id and it was image box and we also had a progress box so const progress box is equal to document document git element by id and progress box as the next step we had um cancel box so const cancel box is equal to document get element by id cancel box and also let's grab the btn and the csrf token so const cancel btn is equal to document document get element by id and then we will have um cancel btn and finally csrf const csrf and this is going to be document get element by name this time and here we need to concentrate to not make a typo csrf middle where token and i'm going to console log the csrf let me save this refresh here we have a node list and if we go all the way down we need to find the value and here is our csrf all right so this is working so i'm actually going to delete this console log csrf and what i'm going to do is to add event listener on this input over here so whenever we choose a file something will happen and to demonstrate this let's first of all add this event listener so add event listener let's put in change change and then we will have for example um progress box we will refer to the class list and we are going to remove not visible and also let's refer to the cancel box and class list remove and we will also get rid of this not visible visible class all right so let's add something to the progress box i'm going to head over to head over to the main html and i'm going to put in progress so i'm going to save this hit refresh and let's try this out i'm going to head over to the desktop and here i have some images from pixabay i'm going to select one and as you can see right now this um image field has changed so i see the progress and the console button okay so this is working and then we need to actually grab the file the image itself so over here we are going to skip all the validations we are just going to assume that we are uploading images and images only so i'm going to create a constant image data and this is going to be input files and zero so we will console log console log this image data to see what this actually is so i'm going to save this and let's try it out again i'm going to i just cancel it for now refresh and i'm going to select another image and here is our file okay and this is what we are going to pass with the form data so we can actually go two lines below create another const called for example for example fd or form data and this is going to be new form data and we are going to write down fd append we are expecting an image because we have it defined in our uploads as image okay so in the form data we need to also put in the image and then the variable that we want to pass and send so in our case this is image data okay so we also need to put in the csrf token so here we are going to append csrf middle where token and this is going to be csrf 0 value all right so our form data is actually ready to send so below we can put in ajax so we are going to refer to the jquery ajax and here let's specify the type to post let's also put in the url and this is going to be the upload form action action so actually in the upload form let's jump in the main html let's put in action and set it to blank and let's continue so here we have the url upload form action and as the next step let's specify the ink type and this is going to be multi-part form data and then we will have the data itself so this is going to be just fd and as the next step we will put in before sent so this is the place where we will have a function that will do some resets for us and i'll come back to this a little bit later and then we will have x h r and here we will have a function that is going to be responsible for uh the progress so we will leave it uh empty for now as well and then we will have the success so what will happen on the success and here we will have a function which will take in a response and let's also leave it empty and we will have error so here also a function which will take in an error and here we will put some instructions what should happen when an error occurs we also want to prevent all future ajak requests from being cached so i'm going to put in cache is equal to false and let's also put in content type false and process data false in the description you can find the link into the documentation the jquery documentation about ajax so you can read more about the stuff that we defined over here um but for now let's focus on finishing the views so yeah let's jump into our uploads application to the views py file and over here um below the form we can do a check if request um is ajax so if this is the case what we want to do is to do another check if our form is valid and if this is the case we just want to save the form and we can return something so for example let's just go to the top from django http let's import json response and over here let's return json response and i'm going to put in for example message and the message will be hell yeah okay so um yeah this is what we are going to return as a json response so um right now let's go to the main.js and focus on this x hr so what we need to do is to create another constant inside const let's call it xhr and this is going to be new window x ml http request and below we can create xhr with an upload add event listener and here we want we are interested in the progress so let's put an arrow function with an event and let's console log this event okay so i'm going to save this and i'm going to head over to the browser going to hit refresh and maybe also what we would like to do is to emulate um the real conditions so we can head over to the network and over here i'm just going to make this a little bit bigger and here we have throating and i'm going to change this to fast 3g alright so i'm going to head back to i'm going to go back to the console right now and yeah let's i don't remember if i refresh the page so i'm going to do it one more time and i'm going to select some image and we have the image selected however we don't see um any console logs over here and this is because we forgot to return x h r so while we're here let's also add a console log of the response if everything is okay and on error let's console log the error all right so i'm going to save this hit refresh select an image and there it is so here we have the progress event all right so um here we have if we open it up we have for example loaded we also have the total okay so here is how much is loaded uh versus the total and we also have um where is it length computable so in case of the length computable i'll just read you what what is in the docs so a length computable read only property is a boolean flag indicating if the resource conserved by the progress event has a length that can be calculated if not the progress event total property has no significant value okay so this progress event total is the one over here so if we are we have this length computable equal to true we actually can get the progress we can refer to the loaded and to the total and in order to do that we can actually comment out this console look with event and over here we can put in if event and then we need to refer to this length computable so if this is true then what we can do is to create another const and i'm just going to call it percent and this is going to be a loaded low debt divided by event total times 100 all right and um yeah let's console log the percent so i'm going to save this refresh and as you can see here are our results and then we have message hell yeah so if we refresh name strt is not defined so we need to go to the models and of course it should be str so let's save this refresh and here are our images okay image which one and then two all right and there are um a little bit bigger because actually i'm working on a 27 inch screen and in order for you to see anything i had to you know make the browser a little bit bigger okay so you can see clearly what's going on okay so uh this is actually working and let's return to this main.js and let's do some additional stuff over here so what we can do is to refer to the progress box in our html and over here with the use of backticks we can put in some code and we will do this if we find get bootstrap.com and go to progress progress yeah this is exactly what we wanted and i'm just going to copy this and i'm going to paste it over here so this won't work entirely however if we focus on the width so let's find the width um i think i've copied the wrong one here i wanted to copy this one with the width okay so i'm going to sorry about this i'm going to paste this again and here with the use of backticks we can inject the percent so percent and then aria value now let's put in also the percent okay and i'm just going to do it like this so now we have this progress box in our html which should give us the um yeah the progress bar though we should see on our own eyes how uh the progress of the upload changes so maybe let's add a line below somewhere over here let's put a paragraph with um percent and then let's round it up to one uh comma space and of course over here let's put in percent and then let's close off the paragraph so now let's take a look at how this will work going to refresh select a file and there it is so as you can see here is our progress bar so we are really really close to finishing this project we could actually end it over here but we want to do a few things more so um the next step will be to actually do something with this cancel button and to be more precise we want to um simply cancel the upload once we press this button so if it's 100 that means basically the upload is completed and it's too late but if we press it on 95 99 85 83 20 we should be able to cancel our upload all right so in order to do that we need to go to our xhr to this function and somewhere over here we can refer to the cancel btn and add a event listener so here we will have a click event listener so we are listening for the click and then what we want to do is to put in xhr abort and we will like to also do some resets so for example we can put in progress box inner html and let's put it as blank and then with the cancel box cancel box where is it we can refer to the class list and add not visible all right so let's see what will happen right now i'm going to hit refresh select a file press cancel and let's take a look at our database here we have this image so the one that we decided to upload hasn't been uploaded okay so now let's go back and concentrate on displaying the image that has been uploaded in the image box so we will need to refer to the success but first of all let's actually define a new constant and i'm going to do it over here and i'm going to put in this constant as uri url and this is going to be a url a create object url and we need to pass in the image data so this is basically to display the uploaded image if we are dealing with a success so this is basically a static method that creates a dom string containing a url that is representing a blog object in our case and right now with having this constant url we can jump into uh success so below the console.log we can put in image image box and then enter html and this is going to be emg src and here let's inject the url but let's also put in a width of for example pixels and yeah let's close it off so hopefully this will work we will see our image and maybe if we are here at the success let's also refer to the alert box also let's put in in our html and we need to head over to getbootstrap.com go to alerts and let's go with the success one so primary secondary and here is success i'm going to copy it and i'm going to paste it over here and let's change the message so here we will have success fully uploaded the image below something like this and now i'm going to save this go back to our page hit refresh select maybe this yoga file and it didn't work so something went wrong um we don't actually see it so let's take a look at what is actually wrong and maybe this was the case so i'm going to save this and hit refresh one more time yoga and there it is so right now everything is working so right now we have successfully uploaded the image below we have this image we still have the cancel button so maybe we should go take this cancel box class let's add not visible also on success because once we upload it we don't need this cancel button it's too late for cancel for cancellation let's see right now and no cancel button visible so this is working if i decide to select a different image i still see this one so maybe we should make a reset okay so in order to do that we need to go to before send and here what we are going to do is to do the recent resets as mentioned before first of all maybe we can do a console log i'm just going to put in before and then i'm going to refer to the alert box in our html and set it to blank and to the image box in our html and set it to blank as well so right now if i save this hit refresh i'm going to upload an image okay there it is and then i'm going to upload another one so as you can see right now we have the alert and the image gone and then we see the image that is uploaded so let's upload another file to take a look at the cancellation and we decided to just not to show the progress and the console button immediately however we still have this file as the selected one so what we can do is to actually make maybe a set timeout over here and let's say that we will do some resets after 2 seconds so over here first of all i'm going to do upload form reset so the selected file will be gone and below i'm going to take in this progress box in our html and this cancel btn with the class added not visible i'm also going to put in the image box inner html and i'm going to set it to blank and the alert box inner html i'm going to set it to blank so right now let's take a look at how this will work i'm going to refresh cancel and there it is okay so let's add this time this this file okay let's select another one cancel so actually this image image box is not required because we are this image box and alert box it's not required i think because we are resetting them over here um let's see if this is working the way it should one more time so let's select an image yoga let's upload yoga successfully upload it and then let's select another one let's cancel and yeah this is it this is uh this is enough so um yeah i think we can just focus right now on the error if something goes wrong so also if we abort we should see an alert box with an alert instead of success we will have danger and then we will have um oops some thing went wrong let's save this let's refresh and oops something went wrong and right now this should also disappear or or we can leave it like this but yeah maybe let's let's get rid of this so um once we uh decide to cancel let's actually put this alert box in her html and set it to blank and let's do it one more time so just to be sure that this is working properly amusement park picture is being uploaded there it is i'm going to select another one yoga we are uploading yoga oops something went wrong perfect this is the effect i wanted to achieve and yeah i think i think we are done with this tutorial so i hope you guys enjoyed it if you did please consider subscribing to the channel if you are new new here if this is the first video uh from my channel that you see a lot of pretty cool content is coming up i have to focus right now on releasing the fifth part of the crypto application which will cover django channels and before i actually want to release the first part of the friendly introduction to django but i'm not i'm not done with the series on django with javascript so i will prepare a few videos on this topic to the series of the videos that already exist for example we will do image cropping we will have select forms so one select input will depend on the other and stuff like that so once again if you are new here consider subscribing to the channel it will be a great pleasure to have you here and yeah see you soon take care and bye bye
Info
Channel: Pyplane
Views: 9,402
Rating: 4.9487181 out of 5
Keywords: file upload django, django and javascript, progress bar django, progress bar django javascript, file upload with progress bar, django tutorial 2020, web development 2020, file upload, django and javascript integration, django and javascript tutorial, django javascript integration ajax and jquery, ajax file upload with progress bar, file upload progress bar, upload progress bar, web development with python, how to, progress bar, django with js
Id: lx0I_nsxvPc
Channel Id: undefined
Length: 46min 49sec (2809 seconds)
Published: Wed Oct 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.