Django Rest Framework Series - Image Uploading / Handling with React Front-end - Part-8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome back to the django drf and react series this is part 8 i think so so far we've built a simple rest api with django and a front end with react we've looked at permissions and view sets and routers very briefly and then we've applied json web tokens we've then headed across and had a look at api schema and documentation we've looked at filters and search and crud in the previous tutorial so if you're interested in any of those then please head across to the playlist and have a look at these other tutorials you should be able to follow this tutorial without these tutorials but by all means head it to the start and go from the start and i'll see you a bit later because there's quite a lot there so let's head over to this tutorial so again welcome to this tutorial we're going to be uploading images from the front end to our back end restful api we are using react for our front end so uh go ahead first of all and build the views and the urls in django and then we'll head over to react and have a look at that so as we're going through i'll give you a little bit of detail about some of the different technologies and a little bit about troubleshooting how you might try to troubleshoot some of the problems that you're bound to occur when trying to apply this to your project so here we are back in django this is the application you can download in the description so once you've downloaded and you've got your virtual machine running like we've done here well first of all we need to first of all we need to i'm going to repeat myself we're going to need to install or pip install pillow because we're going to be utilizing images and manipulating images and so on pillow is going to allow us to perform those type of actions so let's go ahead first of all and install that so i already had it installed there you can see but it doesn't matter so now that we've got that installed you can update your requirements file if you want to if you've not done this before it's simply a case of freezing and then selecting the file so that's going to just update our requirements file here and you can see it's added a few more different packages here other than pillow so some other dependencies it looks like we're going to require so now that's done let's just uh close that we now need to make a new folder here on the project level we're going to call this folder media now you don't have to call this media it just seems to be like a digital way of working a general standard way of working so with course media this is where we're going to save all the images that we upload and where the image is going to be served from to our front end so next up we need to go into the core so this is the main project folder settings and at the top here i'm going to just import os so i'm going to need that to set up yep i'm going to need that to set up the media folder so at the bottom we're going to add a few more lines here so now that we've actually got a media folder we need to tell django where this media folder is so it knows where to save the images so we can do that by finding two items here the media root so we use the os that we've just imported get the path and then join the essentially here we're getting the the path to this directory this folder directory here where the actual django installation is installed here and then we're using the media folder so if you wanted to change the media folder to something else you'd need to update this string here and update the media url so we're going to use the media url the front end when we request items from our django backend we use the media url to direct the url to the media folder inside of the media folder is obviously where our images are going to be so that's why we're going to need the media url so that we can access the images from the web so now that we've got that in place we can now go ahead into the blog actually there's one thing that we can do to serve media files locally if we go into the core urls what we can do in here is just to find the fact that we're utilizing at least in this production development environment we're utilizing the media folder so sometimes we need to just need to set that up so here i'm importing settings so i can access the media settings we've just defined and also static so that i can then go ahead and just run this url pattern here and just defining the fact i'm utilizing a media folder so again that's just going to allow me to work with the media folder locally right so now we've got a media folder we now want to obviously be able to actually upload images as well as the post information so if you remember the blog has the model for the posts so you can see that we we have category title x etc that we've been doing in the previous tutorials but now we want to also add an image to this so we can do it right here now what we're going to do is first of all define the fact that we want to have an image field so we can do that i'm going to call mine image model and then i'm going to use the image field excuse me i'm trying to zoom in and you can see what i'm doing here is i'm using an underscore so this essentially here is just a recognization of what this field is a description of this field which could be translated into different languages so what i can do here and what can be considered as good practice anytime there's any text that could be translated into other languages we can just define it in that way so we utilize the django utilities translation and we import the get text lazy and then we define it as this underscore here so we're assigning get text laser it's the same as i'm putting this here for example except for we're just assigning it an underscore to make it easier to and use utilize less code so that's why we've got that there and you can see we've used to upload to and then we defined a new function or we're going to define a new function called upload2 in a second and then in addition to that so that we can easily add this to our existing model i've added or included the default so this is going to be the default image so if someone doesn't upload an image for their post it's just going to use the default image so obviously you need to make sure that in your media folder there is a file called default in the post folder okay so what does this upload to so we want to specify where we want to upload our files so what we can do is we can actually create a function i'll create a simple one at the top here where we can actually upload or define where we want to upload so here we have upload two the function i'm calling i'm taking in the instance so the instance that i'm building so i'm building a post i then press submit and then that's the instance that information and then the file name so i've taken those two parameters there and you can see that i'm just returning the fact that i want to save this image to the post folder and then utilize the file name now a common mistake here is to think that you can utilize the post id so unfortunately you can't use the post id in this instance here because this is being performed before the data is actually saved so if you want to use the id you'll need to perform an action after the post has been saved and then potentially rename the file that's already been uploaded so that's a a tutorial in itself almost and i did promise others that i would create a tutorial focused on imaging managing images in django so we'll definitely do that in the future but here's just something simple so you can get started changing or defining where you're going to save your images so now you can go ahead and migrate so i'll go and do that to make migrations now here we got a problem so you can see here we've got a nullable field excerpt now this is just a mistake that's been made so if this happens on yours you just need to i've remove it um or just change this to true so with that done we can now just make the migrations and then migrate obviously you could go for a dry run first if you wanted to and there we go so now we apply that so we now have this field ready and available in this model so let's now go ahead and go into our blog api so what we can do is add this to our serializer so after title we now have image so we'll just add that to our serializer so we're going to utilize pretty much the serializer every time we upload new information so we've added that into the serializer i just want to double check actually i've done that right i've called it image yep so it's definitely called image that's all we need to do there so let me just close down so now we can go into the views so the views at the moment we've got display posts just some generic displayed posts we've got the post search at the moment and we've also got some admin still which as you'll probably agree if you're familiar with doing development in django it's not the most effective as i've already explained before but i've done it for a purpose so that we can refactor it later and talk about different methods of slimming down and refactoring code so now what we want to do is utilize this create post to actually also insert an image so we want to upload an image that's what we're trying to do so i'm just going to toggle that out for now and i'm going to just build a different class for this so let's build a new class i'm going to utilize the api view in this case so the api api view is pretty much the same as using a regular view class and it allows handlers such as get and post so we'll just do some overriding of this just to show you a different way of creating a more manual more precise potentially provide us a little bit more options when dealing with data and so on than what you've seen here which can be a little bit abstract so let's go ahead and first of all we're going to create our permissions so we can utilize permissions as per normal so remember we are using jwt in this scenario now we've covered that in a couple of sessions we couple covered that a couple of second sessions ago so we add that in and now we're going to be utilizing this parser class multi-part parser and the form parser so i'll explain that shortly let's just go ahead and complete this view first and then move back to that and what that does but essentially what's happening here is because we want to upload images and text for example there's multi there's multi part data there's multiple types of data that's being uploaded and we need to be able to handle that so that's essentially what's happening there but like i said we'll swing back to that in a second so now we're going to create a function called posts so what we're going to do is handle what happens when we actually post a new items now i'm not entirely sure why i've called it user avatar upload i think i was using this piece of code for another another tutorial so let's just um call this um post upload or admin post upload okay so next up then so just to finish off this function here so that's been normal we're using self to take in or give us the ability to access other variables etc outside of the function we've got request so this is the user request so we take in the request to remember the user makes a request um from the front end so we take that in and we also have format none so here we're basically taking advantage of the fact that our responses are no longer hardwired to a single content type remember we're using multi content here images and text so here we place it format none so it's a little bit of a curveball because it's worth reading about formatting on what i've just said there really what it's used for you could argue that we're not actually using it but i just want to introduce it there for you to have a little bit of research okay so this essentially means that our api will be able to handle urls such as um one two three dot com forward slash five dot json so if you have a look at the rest framework it's worth seeing that type of thing to utilize different formats in our urls so let's go ahead now and fill this in so we've got print so i wanted to explain and we'll see this much later on why we've got print here now there's bound to be problems and issues here and one of the biggest issues that you'll probably come across when you're using apis is that you get a bad request of 400. so normally why that is is because the data you're sending across is not in the right format for your serializer so if you want to capture the information that you've sent across just before you hit the serializer and obviously it will cause issues because the data you've sent across if it isn't correct and doesn't match the serial serializer it won't work we just capture that before we get to the serializer and that's going to give us some diagnostic data that's going to help us understand what it is we have a problem particularly like i said when we get the 400 bad request so next off we serialize our data as per normal and we get the data from the request so we take the request in inside of the request is data and you can see here we've extended here and we've actually then requested that data and we put it in this data variable here and then we sent it across to the serializer so why i'm showing this example is because now you can see that we can perform different actions based upon whether serializer is valid and so on and if the serializer is valid we can perform other tasks whereas here in the generic classes here everything is in the background everything is abstract yes we can extend etc but just wanted to show you an extern example here of doing this in a different way so if our serializer is valid so if our data that we sent across is valid to the serializer and it will be capable of actually inserting into the database then we're going to save the data and then just return a response so this is a handy tool to include because we haven't really spoken about this or started to implement this in our project yet actually sending messages from the back end to the front end in terms of um error messages so we've done a little bit of handling messages or error messages on the front end only but not front to back and i think that is worthy of its own tutorial and we'll definitely look at that in a later tutorial in this series so here we can return response for example if we don't have a problem so this is in the if now of course if our data isn't valid we're then going to do the else and return back a response of 400 pub request so how we generate that is through status so we can actually now just import this into the project so as you might imagine at the top we're just going to import status in so we can kind of grab and utilize those or formulate those response codes to the front end so that's status and then in addition to that because we're using utilizing multi-part parser and the form parser from the framework parsers and we're using both of them here we just need to import that in two and that should make up that right there so now we're kind of good to go there so let's talk a little bit about this multi-part parser and form parser and what it's really doing for us so what's important to read through in the django rest framework is if you go to the api guide and then search for parsers and here one of them is specifically the file upload parser so there is a a parser that's um dedicated to file uploading and it's going to look like um i think it's called file upload parser so we could just use that for example if we were uploading a file but of course we're not just doing that we're sending across form data that's what's going to be parsed here so we're going to send across form data and in addition to that we're also going to send across our data that includes the image so we're going to need multi-part upload support so by that i mean that we're going to send multiple different types of data so image data and text data so we want to be able to in our request break that data up so we're sending multi-part uploads and this is essentially for web-based uploads and we've been told in the manual in the django rest framework that we need to utilize multi-part parser so that's why we've got multi-part parser and also the form parser as it says in the manual also typically you want to use the form parser and multi-parser together in order to fully support html form data okay so um let's now i think we're finished off i think we're finished here in actual fact and i think this is all that we need to do here so this is essentially going to just to recap handle the uploading of our new data particularly because we're going to be sending across um both form data which includes text and an image so that's going to handle that right there and you can see that if it meets our serializer guidelines so this is obviously connected to the serializer fields are connected to our model our model defines what we can actually include in that particular field that's how it's all connected there so as long as it matches or meets the serializer criteria our data we're obviously going to save that data and send a response back so now we can head across to the urls because we're going to need to set up a new url for this so originally we had this path admin create so i guess we'll just use that again so we'll just change that around so now it's called or an actual fact we might as well just use the old the old name can we so let's just change that to create post and let's uh just make sure that's connected so we've we've got create post up here and we're importing it in so that looks like that all that looks like all that we need to do to get that working so that's all now connected up nicely okay right let's just go into the settings of our core we're just going to turn off and i know that i do this fairly regularly and you don't we don't need to do this but i'm just going to turn that off just to make it easier for us to test this before we do anything else and i'm gonna open up um what is postman so this is something that i introduced a couple of tutorials ago so this is a piece of software called postman this is just one way of you're actually testing out your api and this can be a little bit more graphical based um you can see that we can save items we can use curl for example but again this is a little bit more graphical based we can save items and so on you can see here i've got tabs at the top here for different requests i might want to send my api to test it so this one here has um been set up to send um let me just set this up for you so we've got the post i've selected body and form data then i've selected file in one of these keys here and then that's allowed me then to upload or select a file okay so you can see also i've added all the other fields that i'm going to need i just added some dummy data there and once i've got that in i'm just going to point it to my api now i have turned authentication off so the reason i did that so i don't have to also play around with web tokens here i could obviously do that very easily in postman i could save my web tokens in a variable and then i could run this etc but it just prevents me having to do that and it takes literally some a couple of seconds to turn off jwt so let's just send and see what we got so at the moment we couldn't get a response because our server's not actually turned on so here let's just um oh wait let's just go ahead and do that i think i've made a mistake there okay so let's just go ahead and run the server so now we send it again okay so if you do get a response like this it's because there's a problem so if you just get something like that that's not what we're expecting back so there's there's just got to be a problem here so if you look at the url it doesn't look like potentially i'm focusing on the right place so let me go back to the url so what i should be looking at is admin and create so again i need to change that press send there we go so it says authentication credentials were not provided which is interesting so if you remember if you go back to your views we do have authentication set up so i'm not actually logged in so i'll just remove that quickly so we can test this out so i'll try this again and there we go so we sent off some fake details you can see we've updated this image here now it says here that we're using media post default which is interesting because remember that's the default for that's the default image that we're utilizing here in our model so that tells me that this image isn't uploading properly now you can see that everything else seems to be okay so let's just uh move that back down again so you can see that this is called avatar whereas our if i go into the serializers we're looking for image so this is why it's not working um so again this is just because i was using it for a different project so but it just gives you an idea of some of the problems that you're going to have so now i've called it image again make sure that there's a drop down here file make sure it's called file then you can upload an image so i press send again and now what i get is a message this field kind of is not unique so the reason it's not unique is because one of these items here has to be unique and that's the slug so we carry on and we do this add some more text to the slug here to make it unique so i've pressed send again and there we go so now what you see in this list just about on your screen maybe um is you've got id title and you can actually then see the image that we've uploaded and it tells you also where we put it so let's go back into our project now go to media go to our posts and you can see we've got an image here called asd.png and there we go that's the image that we've just uploaded so that just tests to make sure that it's working so i am focusing on this troubleshooting because you will have many problems no doubt trying to do this there's a mixed message online looking through some of the materials etc to see what people have already done try and make something a little bit different for you um but i ended up just trying to solidify what is out there and i'm gonna try and give you some feedback in what you might see if you're trying to perform this and looking at different materials so what you'll notice that when we've uploaded file you can see in the console now this data this query dick here is query dictionary so you can see that the image is uploaded as an in-memory upload file so what this is telling you quite clearly is this endpoint works okay as long as we're using um in this case let's have a look at our body as long as we're utilizing the correct data and we're uploading the file and it should be a file and we're using form data this data is inside of form data which we'll talk about in a minute when we get to the front end then this should work so try and utilize this as a guide if i go into the code you can um in this program if you're utilizing for example node you could click on node and it gives you the code now to actually run this query or sorry to run this request and you can just copy and paste this into your program same with php and so on so i just wanted to quickly show you that if you're utilizing this for different programming languages it doesn't have um it has javascript fetch which we could use in actual fact and then just change it to axios i suppose we could use it for that potentially so it does have code that we can utilize which is handy but if you go into for example the headers we can see what we're sending across so you can see the server the content type now notice the contact tent type says application json which is fairly interesting potentially here that we're sending across and there was something else i wanted to show you and i thought it was in code but it's not okay no problem uh so you can see that it's working okay um so let's now move across and go to the front end and then apply all this to the front end so that we can upload images and then display the images in our react application okay so before we actually do that let's just um put back our permissions and then go into the settings and we just um add our jwt back so we've got our authentication back in place and go ahead and download if you like the react application that we're going to build from it's in the description a link in the description and i'll see you over in the react application so just to quickly recap what we've done so far you can see that we're building this really simple blog facility these posts have been generated from our django backend we're inside of react now if you're wondering where we are sorry i'm talking very quickly so there aren't any images i've taken those out now we're going to actually generate those images for the post through uploading it first to the django backend and then we're going to use our api to collect those images as well as all the data that you can see here so we can click and go into the individual items so we've done the single page and we can also search for items utilizing at the moment just uh individual words that have to match the start of the actual item we're looking for so we've got django and i think we've got react there we go so we've got two items there in the search so we've done that we've got log in and log out and register that's all working using jwt authentication um and in addition to that in the previous tutorial we created the admin area where we could create return update and delete items if we wanted to um so that facility is now in place so now what we want to do is create the facility to create an item but also include an image okay so let's do it well that sounded really positive okay let's do it uh so let's go into our react application let me just um size this up a little bit okay right so um let's first of all just deal with setting this up so i'm just going to close all and we've already got an existing create file so all we need to do is overwrite that so what i recommend you do is just copy and paste that first and be before you start playing around with anything um so i've copied and pasted that so if i need to go back to it i won't need to put just a little um just a little strategy to ensure that you don't mess things up i guess well that sounded really positive so let's go into our project here we've got create already if you remember so we don't need to make any new files here all we're going to do is overwrite or change the create item so let's just remember that axios is right here in this in the project main project folder area and you can see that we're just extending from the access instance to generate a request and our request at the moment includes our access tokens if we need to send those across to authenticate we will do every time we make a request and you can see that the content type has been set to application json and we accept back from the server application json so that's what we've got back here the code down here is just going to help us to if you remember from a previous tutorial it's going to allow us to generate our refresh tokens so that we can stay logged in so that was the access file in case you're wondering about that and you can see that we've also got our base uri or url already set out so we just need to extend from that when we create an instance of or an axious instance from this okay so the first thing i guess is to add a new item in our grid in our existing grid so head down to around about line 190 you can see that after the last grid item which is the item or the input field where we enter the content we're now going to put a new input field now this isn't like we've kind of moved away here from material ui just for this example you can see we've got this input here which takes accepts an image and then define what type of image maybe any type of image we've got some glasses if we want to add it up hook it up to some css we've got an id here um so icon button photo for example um something like that so let's just call this post post image there we go um so let's just call this post image and we've got the on change so we're going to perform an action when we change in this case it's going to perform an action when we upload a file and it's basically just going to be stored in state you can see it says name image and file type is going to be file whereas normally we don't define those on the inputs so we're defining it's going to be a file so there we go and then we've got this little label here if you want to use a label i'm just going to get rid of the label not going to need that for now okay so that's pretty much all we're going to need there i'm not too sure what that is um so i'll get rid of that as well okay so now we've got our input field let's have a look to see what that looks like so if i go to new post we've got this button here you can see it's not been styled i may style it before i upload it but it's functional that's all i want to show at this point so i can choose a file and that should allow me now to choose a file so let's go back so what we want to do now is handle that so when we submit this image sorry now when we submit this image we're now going to utilize the handle change so handle change is basically taking the data that we're typing in in the text fields for example and it's just uploading or saving it to the state so we just need to change the handle change function to include also the image so we've given it a name of image so that when we want to manage this data in the handle change we can identify the data from the name and do something different so that's important to remember so back up here then in the line 70 here we've got handle change so you can see what's happening here is that every time i type in something into an input field this handle change is going to be utilized so you can see that if for example the target name so remember the target names every input field has a name and if a name equals title so if i'm dealing or typing in something into the title input this is going to be run so you can see i'm updating the state so i've got two states here which i'll explain in a second one for the image and one for text so this is going to update the text state and you can see i'm taking the target name and then basically i'm just going to trim that any for any white space etc and then put it in to the state up here so i do that now at the same time if you remember from the previous tutorial i'm also updating the slug so the slug is going to be sluggified utilizing this code here as a link to this piece of code it's basically just going to slug sluggify the text so we've got that in place and then we've got an else here which is also then going to just upload any other text we type into the other input fields and put it into the state and of course what we're trying to record here is the title slug excerpt and content so let's go ahead and add a new item here so what we're going to do is we're going to basically target the image this time so if the name equals image so if we upload something to the image field or use the upload input for the image then this is going to be run so what we're doing here is we're taking um the files so whereas before we're utilizing value on images we're utilizing files i guess that's the important thing to focus on here now some people will also utilize for example xero here to represent what file we're uploading um that isn't going to work in this instance but if we were uploading multiple files or trying to return multiple multiple files that's how we could reference that if we were using an array so we're not using an array this time we're just utilizing we're just going to set up a basic state for this here which is set to null so this is where we're going to post that image inside of here so we utilize set post image to actually set the data and then we're going to utilize post image to get the image data later oh so um we've got this console log now that's obviously optional whether you want to just output that just to check to see what you've been what you're actually storing but i'm not going to need that right here so i'll just remove that and i'll leave that so we can see it sorry in a second so you can see i've updated the image there otherwise i'm just updating the state here with any other text okay so hopefully that makes sense if it doesn't just let me know and i'll explain it in the comments so now we're saving the data uh if you're wondering where all this other code comes from if you've not seen the other tutorials we've been generating this for the past seven tutorials so if you are interested head back to the start and go through so now we need to manage this data so what's pretty good to do maybe if you're not familiar with utilizing axios or sending data across is to not try and tackle again only if you're not familiar with um or you're new to this type of development try and do something individual first and then integrate it in so for example here we have the code which is going to explicitly send off via axios the data that we've inserted into the form so up here i've got the code which is a little bit more slimmed down so um if you remember what's happening in this project for example here we're going to import axios instance from the axis file and we're just going to extend from it so we use the axios instance that's been detailed in the axios page to then send off or do something but here what we're going to do was trying to get to was the fact that let's just start off explicitly and then we can work towards slimming it down and refactoring so here what's going to happen here is we're actually just going to use axios itself and we're going to set up all the parameters so let's just make sure that we've got it installed or available and we do up here so let's just go down uh okay so what we're going to do you can see we're going to set up a variable here which is going to define the headers so here what we're doing we're defining multi-part form data so we're just specifying and telling django that we're using multi-part data so that just matches up if you remember the data that we set in the django ins wherever that is um somewhere we've set that up earlier in django so we've defined um for example if we go into the views we defined we're using multi-part parser and form parser so we're just kind of matching that up with the the header type so we're just telling django that's the type of data that we're sending across and then we set up the url now this url is wrong so let's just go ahead and change that so we change the url if i remember to admin create so let's just make sure we've got that in place that's where we need to send it and now we're setting up our form data so we're specifying that we're utilizing form data so think of this as a format of preparing data to be sent across so what we're doing here is we're just preparing that data inside of our form data here um so that it can be utilized correctly with multi-part form data and then in addition to that we also want to make sure that when we return the data that when the data gets parsed it gets parsed in that format too so this is where sometimes it can get tricky to understand why something is going wrong and this can be one of the most common causes of problems because the data isn't in the right format so if you remember previously in axios for example or any other file we're utilizing application json so the program is just expecting json format database to be sent across and then hand handling that data so here we're using multi-part form data so we're generating some form data here so let's just explain that so of course go ahead and type in what is form data form data provides an interface that easily construct a set key value pairs representing form fields and their values so it sounds very much like json if you ask me so you can see how we're going to set this up of course we could just loop through the data here but this is just explicit for you so you can see what's going on so we create some new form data and then we append the the form data and with this new data so the title and then we grab the title from our store so remember we've got our store here which we grabbed through post data that's how we get to this data so we go to post data excuse me and title and then we do the same thing for the slug now we are explicitly typing in the author still because we've yet to do that tutorial where we look at utilizing a a persistent state so we'll do that um maybe in the next tutorial so for now we just hard coded that in the author and then we go ahead and exit the content and then we go to the image so notice here we get the image via post image so that's um this store here and no sorry this store here so this has been saved here in this state so we grab that item it's the first item in the state so we use zero and we select the image okay so because we've saved it as image so let's just remember if we go bit further up here we've created we've selected the image so when the image is inputted this will fire off and this is run you notice that we put it um into the state as image and then the actual file so that's why we're referencing image here because that's what we've referenced it when we put it into the state so that will collect the image okay so now we utilize axios so here like i said we're not using the instance that we've already built we're going to create our own axios instance so that takes in three parameters generally the url the data and the config so we've already set out the config here that's just the headers we've got the url which is going to be the create admin create and then in addition to that we've also then got the um form data so we take that in and we get a result so that should be it now we need to remember and before i forget um we've just turned on security again and we're not utilizing that at the moment so apologies again i'm just going to turn this off for now so that's the authentication and then in the view i'm just going to remove this for now just to get it working without authentication so we head back into the admin and i'm going to new post see if we can type something in i'm just going to pause and upload something so i've selected a file and that should be about it so press create so it looks like um we may have done something um i was expecting us to be returned but we've not done the forwarding yet so and that looks like it might been done so let's go back into the page here so it looks like we've got a new post it looks like it's working okay so that's obviously the first check that we need to do so let's go back into our adaman area and engage posts so we've got a post here now we've got an image looks like the right image um so let's just try this out one more time just delete that so let's just try this one more time apologies i keep pausing to upload an image because i just don't want to see everything that's on my desktop and then so i've changed the file selected the file as per normal press create now just so i can recognize it so that's that so let's go back so we've got something here you can see it is actually working and because i've already put the code in for that so that's all good um so what we can do is just check first of all the django admin now the telltale sign if we've not done something right in terms of the image is that we'll be utilizing the default image so that would tell us whether we've done that correctly or not now something else that we need to look out for um is if we go into the django console obviously this is going to tell us if there's a mistake so let's just um simulate something here so let's for example change the image okay that let's just change um for example this here and then just try and create a new item just so that we can see an error that seems to be a bit bizarre not too sure why it's doing that now so we change the url so let's this shouldn't work of course press create uh now i can see here in the admin django admin it says not found so it will be providing us some good feedback in terms of um what is happening or what isn't happening so it's good for us to keep this on and just double checking what's going on obviously we can see that it's working but this will pick up some nice errors for us when you are troubleshooting so i do have a question for you which are hopefully one person can or someone can answer for me so if i were to code this out using classes traditional react classes etc then this would just work okay if i for example utilize one state for both the image and the data now notice here you might be asking why am i using one state here for an image and one state here for under text well the reason why that is because if you're going to be utilizing hooks in react for some reason when you move everything over to hooks functions um the if you put the image inside of here for example and just use utilize one state what happens is that it just doesn't work so if you can tell me why that is um please do please put it in the comments i've got a rough idea why that is but it's a really bizarre problem and it'd be one that i if i get a bit of time i'll try and fix but you can see here we're utilizing two states here one for the actual post data and one for the image so that was just something else just to let you know about if you are going to try and do this and you are receiving an error because you're utilizing just a single state utilizing react hooks and functions here okay so you can see that it's working so we've got this working you can see this is all manual based so let's now switch over to our axios instance so before we just use an axius now remember that we've already got our axius instance so we can just reference that and it has all these settings already pre-defined for us so we don't need to do as much so let's just go back in let's go to the top let's just remove axios we're now going to be utilizing our axis instance and we also need to set up our redirect so let's go ahead and we're going to just remove all this stuff here i'm not going to need that anymore okay and now we're just going to head over to this here so let's just uh back out so you can see the difference here um i should actually add that in so you can have a look at that i'll just leave this in for now apologies you're going to watch me do this now um if you're wondering why i'm not using short codes on my keyboard because i've got this weird keyboard set up so you can now see that we have a new way of doing this so we put all the data inside a form data as before again you could refactor this down slightly by creating the loop looping through um whether you actually create less code be roughly the same i think um you can see we've manually put in all the data in appending the data and the image and this time we're using the axius instance okay so this time you see that uh we are just sending it off to the admin create and we're just using the data we're not defining the headers here so if you remember the axis defines all the headers including our authentication that we're going to need to authenticate and actually send this data so what we can do now is go back into django apologize there's a lot of switching around here all the time i do apologize but i'm now back in django um so i'll go to my views i'm just going to put back the authentication or the permissions sorry that's in the view for our create post and then if you remember i need to go to the settings and i just need to um put that back and now we're using jwt so we can test that by going into postman and pressing send and it says here authentication credentials and we're not provided which is suggests that authentication is now turned on so let's go back to our front end and just go to the blog you can see it's still okay looks like we all are authenticating now again we can go down into django and see if that was the case um we didn't get any message there in actual fact so let's just refresh okay so that's not a problem there's a not found here because i don't actually have the default image set up that's all that's going on there um okay so let's go into our admin so we need to do that manually still at the moment uh let's create a new post we're going to call this apps and we're going to choose a file so i've chosen a file and then i press create post so we created the post you can see all the data that's being created um looks like it's done what it's meant to do so let's go back into the the home page there we go so now we've got authentication applied jwt is also working so we've got with our authentication also now in place and you can see that we're uploading and now we're displaying so let me just quickly show how to display an image all we need to do is go across to the page where you want to display the image apologies i mean django there so if you go into the post section we've got the post so that is going to actually display the images um so down here we've got the loop whereby we're looping out all the data that's been returned now down here we've got the card media inside the card media we've got the image now how we collect data is that we take all the data that's been returned from the database that's inside of this post variable we then map it across to post and for every single instance inside of this post array here we're going to basically loop it out and now one of the parameters in our data is called slug image and so on post title and so on so basically we're just going to use image and then post title so what was here originally if you remember i was connecting to an api an online api to get some images but now i don't need to because we're going to upload our own images and there we go and there we have it displayed on the screen so let's just um double check again if we go down into apologies if we go down into our media you can see all the images that we have now notice that we're uploading the same image django is renaming that image so there's definitely some administration you'd want to do there to maybe rename the image yourself um or organize it in a way i would prefer to organize this in a way so that all the images are in a corresponding folder that relates directly to the post so what i mean by that is that if i've got post id 1 i want to make a folder called number one so that when i delete the post later on it's not so much of a headache trying to find all the media that's associated to it that's what i think we need to think about when we're creating a folder with images for a particular post we need somewhere in later on to be able to identify that image to that post so that we can clean it up easy so i just wanted to point this out the the fact that in our axios instance we're using content type application json now if i go into the create we're not actually utilizing or we've not actually defined the multi-part form data like we did originally we're just utilizing whatever is in axios application json so you would imagine potentially this isn't going to work so let's just see what happens i'm just going to remove this and explain this in a second and the reload so it doesn't redirect and let's go back into the um new post i'm just going to open up the console so we capture this i've gone into the network tab we're just going to capture this request and have a look at the data so let's just make a a new piece of content add an image press create and if i now go back here you can see that i've created this request here so i go into there and i you can probably just about see here what's happened where i've sent it requested it status code we've got 200. so this has given me some really good information here now i've got some response headers and but further down you can see that i've sent across my jwt token and in addition to that it says content type multi-part form data and also the boundary so it's actually defined what content type to utilize automatically so that's pretty much the point i wanted to make so it seems to be forcing this rather than utilizing the json application content type is actually forced and is utilizing multi-part form data so that's what i wanted to show you down the bottom here you can actually see the data that you're sending so this is of a good resource for you and in addition to that we've got this uh form data you can see we've got this multi-part form data here separated by these form boundaries of the different data data that we're sending across so that's what we're actually sending across so that can be useful for troubleshooting too so just finally then you can see that i've also included a history push so i'm utilizing history so i've imported history in as per normal use history from the react router dom and then we set this up so you need to um set it up first so i put it into a history variable here use history and then i've utilized it down here i'm basically just pushing the user to the admin page once they've created a new post now i'm also utilizing this small hack here windows location reload because otherwise it won't appear straight away so i just force a reload for now so that i can actually see that i've created an item similar to what i've done in the delete and edit i've forced the issue of reloading so that would actually display what we've just completed or the action that we've just taken okay so there we go a small one but hopefully a valuable lesson there on how to upload an image some items to think about maybe a little bit of reading to do and then we've yeah we've uploaded images from our front end to a back end we've also then displayed the image on the front end we've got some views and urls to handle that and we looked at a different way of generating um a view and then we've gone to the react and we just built upon what we what we've already done in the react application by just expanding or just changing the create component to include the image and we created a very simple image input field to upload an image and we sent that across so all in all it is a fairly simple process but one that you can easily get wrong so i do welcome welcome i do invite you to ask any questions that you might have now if you are having problems it can be difficult when you just say yeah i've got this problem i mean it could be a million one things potentially that could go wrong so i will try and help as best as possible but of course there's other services that you could ultimately utilize to get some help so for example stack overflow there's a good site for you to post your code and then people including myself can go along and have a look at your code and then try and solve your problem hopefully i've given you some good diagnostic tools today and some pointers towards that to help you solve some of these issues most issues are very solvable by looking at some of the tools and features i've mentioned today so definitely have a go before you start posting these things can take time a lot of time so keep at it and hopefully i'll see you in the next tutorial
Info
Channel: Very Academy
Views: 16,655
Rating: undefined out of 5
Keywords: django, django rest framework, django framework, django rest, djangoproject, django react, django python, rest framework, django cors, django tut, django tutorial, django 3, django examples, learn django, django beginners, beginners django, django 2020, django example, react, django and react, django search, react django, react api, api upload, image upload api, django image upload, file upload api, django file upload, react file upload
Id: V2zaeqFSSTE
Channel Id: undefined
Length: 58min 2sec (3482 seconds)
Published: Tue Sep 22 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.