How to implement an Ajax Search. Django Project Tutorial[19]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back everyone its Christ and in this video I'm gonna show you how to add an object search to a jungle website up to this point we have been able to create experiences and we can list them here so once ID functionality so that the user can come in here and they can be able to search by amount it can be able to search by the categories they can search by the descriptions and all that stuff they can search by dates okay so they will be doing this is we are going to set up an endpoint that sends JSON and then from our application we can now detect when a user is is trying to search for something and then we can send an API call under the hood or a server and then return those results and update the UI in real time okay so without further ado let's go ahead and get started by setting up the endpoint I'm in my views dot view idea so I'm going to set up an endpoint here I'm gonna call it such expenses okay so here what we take in the request we are going to be able to accept a post request so he is going to be able to if you think of it AJ is going to be able to send send us like a key maybe something like site value and then the value which will be what is already has been put in the search box so we are going to allow for a post request so I'm gonna say if request method equals post so then we need to get everything that user will be sending so since you are going to be sending JSON over the network we are going to need to import JSON yes so we can transform it into something we can search by so once we have once you import JSON now you can get everything that the users is trying to search for likely as such such string by doing they'd say such string will be equal to JSON but load buttloads then we are going to be reading in the data that we we receive over the network so we can get the data from request put body and then the user is going to be sending us a key code like such values but this can't depend on what the user will be sending you for us you are going to pull out our own sacs takes a little time to do to get such text and since we are going to be using javascript and the front-end it's it's common that we send it in this kind of casing become okay but any is fine actually so so right yeah basically what we are doing is whatever we sent on the network we want to transform it into a Python dictionary okay so we won't send an object from Jas and then here we want to transform it using JSON 2/3 to a Python dictionary from which we can access a single key by doing gate so if this does exist actually this will crash so if you ever want to stop it from crashing you can just add an optional empty parameter but for now we will be sending this because they are going to cut the front end also so once we have this now we need to query our expenses mode okay so for us to get the results I'm going to store them in a variable called experiences okay that's fine so now this is going to be equal to the expense model do it filter so we are going to be filtering by the fields here so if you cut our expenses you're going to see that you have these fields so I'm going to pop it in here and then we are going to be filtering by order so first thing is we are going to try to match the amount so for us to match the amount we are going to now do amount then we are going to use underscore underscore that's we'll then you sit equals what is I is trying to search for which we already have in such string okay so what this one means now is we are we are setting the model where the amount starts with David string so let's say if a user is trying to say such 4,000 for us we are going to look to be returning all the results where the mana start with a thousand if they add a zero it means we are going to be cutting we are going to be returning the ones that start with a thousand okay so next it's also important that they use a dozen such for records that don't belong to them so right here we also want to match that the user who's searching who is going to get these results is the one that created them so you can pass another parameter to search for now this will be the owner so the owner will equal to request root user okay so this will basically do the job to such by the amount so for us to be able to get all the results that match you know across all these are the fields we are going to duplicate this one a bit so I'm going to add in an or operator so what this is gonna do is it's going to be getting the charoset that is returned in here and then adding to it another concept that will be returned by this other filter we are going to write so I'm gonna copy this and then here we need to tap this one back so then here we are going to now search by the dates so the debt it's also important that the debt we if we query by stats with because that's when it's unmade context you're saying so then let's go ahead and search for like the description so I'm going to duplicate this one so now here when it comes to the description we would want it to much like all the occurrences in that string so that when someone says I got money on from my friend put some Assizes for a friend in that sentence we can be able to retrieve that record too so for us to be able to do that we're going to use description underscore underscore I contains I contains equals to such string so basically what this is doing is it's going to do a full text search that stream and then it's going to the I means case-insensitive so if you have like ad some way and then a is trying to search for a small D it's going to match that so that's what this means and then it can match across any part of the string anywhere in the string okay so once we have that let's do the same thing for the for the category and then I guess we'll be done for now but then you can see like all the possibilities that are here I'm going to try to leave modern links in the description so that you guys can read more about these filters okay so now this filter by the category okay so this one here when I leave category pertains fine you want to match the user good okay so once we have that okay I need to tap this one in when I do that they use a sense Association so I need a way to send it back at least and the oh we can do that is by using the HTTP response class so from Django HTTP inputs JSON response so we can use the JSON response to format page one that you can send back to the user okay so what this is gonna do now is it's going to contain query sets and it's not easy to work with query set so it can send queries it's over a network so what you are going to need to do is a new query says if they provide the code is fashion pod values which when you call we will done for us at least so when you call various basically what it does is these two terms for us basically the fairies okay so once we have this now we can send it over a network by doing a return JSON response and then we are going to transform response into a list so it will list then you can pass data and then since we are passing a list and not a dictionary of times it can build to be savior right so what you do here you pass safe equals false okay and that allows that allows the JSON response class to be able to pass something that's not a dictionary easily okay so now that we have the view setup course we'll come and test it as we are building that from the front end there in issues you're going to be able to fixed and then okay so once we have this now we can go back to you and set up orphaned all right yeah you know index dot HTML I'm going to scroll back to yeah on top of the table and what other room then inside I'm going to have two columns so one is going to type of eight columns and this should be called so call m.d. eight I'm going to request for two you know of course I'll change the second one if over phone tradit there twelve and in the second one now I'm going to set up a phone so yeah I'm going to have a homegroup and inside I'm going to have a phone control so in here actually this should be input no it's just phone control okay so let me fix that so input from controller so I'm going to give me the placeholder because such yesterday is a knows what it does so once once we have that what we are not going to have like a submit button but you're going to be able to search when a user is typing in his details but you can as well at the button if you need to require that a button to submit if you need to require that okay so once we have this if you go back to a view and reload okay we have been logged out to the middle bin how interesting okay so now you see that we have this search view so now we want to work on functionality Topeka to pick a text as the user enters it and then such is phone okay so to start with I'm going to to now pick this this text okay so to provider of picking the text right here I'm going to add an ID attribute so we can refer it to eat in the JavaScript so I'm going to call it such input such field actually so I'm giving it an idea of such field now we want to create a JavaScript file that we can refer to so right here we need to load static for the content static so once we load static now we can reference our static files so just here before the before the end block I'm going to create a script and by the way you can write to your JavaScript here but then it's good practice to separate your JavaScript and HTML so right here I'm going to add the sauce so sauce will be jeaious slash much I'm going to have such expenses so J is fire gets to do specifically that but of course you can use organize this beta alpha now we will work with it this way so if you go to our J's files ideas so that should be in our main app folder in static 10 years so here we can create our fire just gonna be such expenses which yes okay so now we need to pick the phone thus the in the such field so you can declare it to such field it's gonna be document query selector so I'm gonna serve this by the ID so you can do such field okay so once we have this now we need to detect when a user is typing so for us to detect when a user is typing we are going to attach an event listener which you can do from side by side field and event listener so the event we want to listen to will be the key app yep so this is going that gets cold every time a user is typing something so when it's cold we want to run a function so it's called basically to turn it as an event now right here we want to pick out what a user is searching for so right here I'm going to declare a value so cost such value this will be put in pinch target get value and this should be a dot okay so this should return for us what is a is dating in every keystroke so now right here we can check if we actually have a search value so I'm going to say if such value value dot length it's greater than 0 then we can such right yet if it's greater than 0 I'm going to be a constant loop just no that's just to check if we ask still on the right track ok so coming back to the app I'm going to reload here you can see that's a logged in me open up my JavaScript console we have an issue already so it's not able to locate our such expenses fire so for example even when I type nothing happens so we need to look at that so basically if we take a look if we if we close early take a look at how we are bringing in right if a static files for example in registration you note that we load static which is one and then basically they were we load our our Jas is we have to prefix it with static and then we can do that what it is so right here so I'm going to copy this and then I'm going to have it here and then we are going to replace it with what we have just so you can have the scene that has corruption so once we have that if we come back and reload that's see that the area is gone if we start typing you can see that we get the user such string so now that you have it we have to we now have to make an API call to a web server so that you can't see if we can get any results and also display them if they are there okay so for us to do that we are going to use the fetch API - all right here don't you need to make a request using the fetch API so I'm going to actually start up from something with eating's invalidates user names just so we don't like spend a lot of time trying to write this and code okay so right here we make an API code using fetch so I'm going to copy that then come over here then have that code here so we are going to be making an API call to expenses around the route is going to be called such - expenses okay so we are going to be sending a search value so this is what you will get such we are going to be getting here inside text so want to make sure that what we add here is exactly what the server will be expecting okay so of course the value now will be the search value and then I want to first trim it just to make sure that the user is not sending us like empty white spaces so we actually have a search variant so the trim basically will remove those white spaces at the end and at this type okay so once we have that we are making a post request we want to - now map it to Jason then another promise will return for us the data so radium went green tuples are going to be doing a lot of more custom stuff so I am going to print the results cloak the results just so we can know if we are returning to raise em so let's go back and map our URLs so if you go to where our views with UI you can see that we set it up but then in our URLs we haven't added it okay so I'm going to copy this bring it up a bit so the URL is going to be expenses such then you want to make sure it's matching here such expenses such a expenses actually sounds more straightforward so we want to make sure it's the same and of course we don't need this payment parameter okay so make sure you have that then have a comma here so then the view is going to be such expenses then we can give it a name unique name also so it's quite such expenses when I'm good okay so now let's test it out so by default there is only an issue that basis there is an issue that I worries that I've already spotted okay so it's going to require us to send it in cross-site request forgery token but for now what you are going to do is you are going to use the other decorator to actually not request for that require that token on this view to show you how it looks like see this decorator here so this is the one we are going to use and the widget is we imported and then we wrap it around our view okay so let me put it here and then we wrap it around our view if you look at our normal navigation you can see that our expenses in the default namespace so when we are searching for them like for example like here we are also going to need to prefix such expenses we can actually search by just searching such expenses okay so once we have that now let's test out and see what we have so if we come back to the view we start typing you can see that we have an internal server error we come back to the server we can see that it's saying type object explains has no attribute filter okay so let's look at it okay so using expense dot objects so it should be good object it gets probably noticed at that filter so I'm going to make sure it's we're using it's like here also I'm going to make sure we're having it correct here same thing object filter of the filter so yeah I guess that's it let's try again if you read the word so now if we search you can see that you have another era if we let's look at it so it's saying and supported lookups that's we for flowed field or join field not permitted pub cement used I start with okay so let's use I sad sweet so basically how that works is it's going to be able to search case insensitive which actually makes sense in this kind of way okay so let's try again so it's another error let's look at it let me reload okay there's another error so this one is for the for the dates so let's also use I starts with okay try again and by the way since this is the front end and we are making the reverse using Ajax which I don't need to to refresh the browser to get stats the new changes on the server so how if you put D you can see that you get the results so you get data and data has one item so in one item if we take a look I'm trying to see what matches okay so the means search for something like Alvin okay so you can see that our results keep getting filtered for example here we had all of them like contain but let me search for this value here so when I search for that we will remove the zero you can see that we get one st. back you can see it is the one with the three this this amount so if we search for like travel then we hopefully should be getting so if you search for a travel you can see that we get one item returned and then if you look at it you will see that the category is trouble okay so which makes sense so if we search for a string like bro you will see that we get hurry returned back and all of them should have bro in the description actually meaning bring this one here so you can see this one has brewing it this one has brewing it okay so this is how they I contains works which it's gonna set through the string every one of you every what occurrence in a string it's going to search across all of it which i think is something that is like very robust robust and very powerful okay so now that we have the results being sent to us now we are remaining with depressing it here we won't set up something good we are going to set up an output area so another an output area basically will be like a wrapper so when I use a setting and we have results we are going to take away bits view and then show the output area okay and of course you could approach this one in many different ways but for now that's approach we are going to do okay so if we come back to our index.html so first thing I'm going to to put everything in the pagination a native the cultural opportunity we are not going to be paginating the results because you could do it before now we won't be ok so I'm going to create a Divya so Dave okay so this one here I'm going to make sure I wrapped everything and then this one I'm going to give it a glass of regeneration [Music] container just so I can have a way of hiding it when we ask such Inc okay so let me actually first to do that so you know I registered with J we know statics is right here we can say if so if we look at the result you can see we get the list so if we don't have results still we get a list so for us to know if we have result we are going to be to be checking the length of this new thundery so if data dot length so gonna shake if data length equals zero then of course there we are going to want to show a user something okay so if the data is if the length is zero then we want to eraser the results we are not there which now we can do by setting up an output area so here I'm going to copy this table the table we already have so down right here pointed up another div I'm gonna give it a class of table output okay so right here I'm going to remove the T the results so I'm going to remove this row here and we are going to be populating it dynamically so first thing that I'm going to do here is hide it by default so right here I'm going to France it so first such out table output this will be equal to document query selector it's so if this by its class and then we want to hide it by default so table output dot star should be style dot display equals you guessed it none okay so once we get the results we want to hide our current table and then show this output table so right here once you get the results we can say table output let's take this gray it was look ok so first thing we need to have a way of hiding our table so I'm going to also get it and put it in to a deal so I'm going to call it I'm going to give a div a class of up table can have the table there so now we are going to hide it when we have the results and ensure the output area okay so right here we need to first first get access to it so we are going to select it by its class which is a p-- table okay so I'm gonna call this one up table then down here now we can hide it so up table layer is play equals none okay so if if the data if the data if the return results have no matching result so in other words if we have the length is zero then we want to add something to the table output sorry if it's really not going to do table output don't you know HTML then I'm going to add a paragraph that says your results didn't match okay I'm going to set it to no results fine okay so it's fastest that's what we have now so if you come back and reload we have the Nommo out the norm of U so if we start typing like T you can see that we hide our parent table and then we show the table that should show our should show our results so right yeah if we keep typing and then we don't match something you can see that we have no results found okay so which is what you want now let's go ahead and hide hide this pagination and then and then go ahead and populate them okay so to hide the pagination of course you need to refer to it so if you scroll down you're gonna you'll notice that the pagination is wrapped into pagination container so let's copy that and then we need to first select it so let's select it by a class name and then I'm going to call it pagination container so once we start searching going to decipher it to hide it so right here style.display because none okay so that you don't that should hide it so let's check again reload start start searching it's gone but then our results are set setting it's gone but then we have a problem here so when a user actually has cleared out of the field we should be able to present like a previous field so for us to do that we are going to now see when the length of what is there is not greater than one in other words here it won't set up a nurse and and in this part we are going to now show back the table and in the pagination so what you can do by app table display equals block and also the pagination is clay equals look okay so let's paste that one out to come over here and reload stop typing it's gone then clears out you can start to bring back everything okay so notice that we also still have no results found here so we also want to remove when the user has cleared out the input we'll just come over here also bring it down you can actually do this play it style display equals none well display close man let's check it out come over here start searching to move you can see that everything is now cutting friend okay so one last thing left is now to populate this data as it comes from the server okay so for us to do that we are actually going to start off by looking at what we have a format via we have right now so in the index dot HTML you will notice that we ended CDs okay so in the in the tedious you notice that we show this wrong and then the edit button but for now I'm going to be focusing on showing the results and not the action but you can easily add that so right here once this is greater than zero so we can add a news now we can select the table header so which we can do and you put this code here we'll come back to it so if we come back to our our such output which is table output which is here so you notice that we have a table T body so on the T body I'm going to add a class that so you can easily select it so put a table body so now this one here I'm going to come over here in the in rjs refer to it so cost t body so this will be document query selector I select it and then here we are going to to obtain some rose to it so right here it's if the results are greater than zero then we can do t body touch in HTML then we can do plus equals so here we're going to use this template uterus because you are going to be adding some dynamic data from here so right here I'm going to add it here and then we need to add these stickies okay so cut it out okay so bring that one inside and now we need to bring in this dynamic very okay so right now we get an array so before we even append to it we're going to need to first look through the array so go right here I'm going to write the roof so I can do data put for rich then of course can have like item then inside here now we can do this so you can show a row for each item okay so for each then we need to post close out this and remove it from yeah so for each we show arrow and then now we can show the different attributes so right here we can now add a dynamic attribute so this will be item but now we are going to match our how we are laying out our TT edges so the first one will be item good amount which you can do now item dot amount the second one will be the category I'm gonna copy this a bit here also here this is category and then this is the description then the third one if they did is they also need a date you can put data okay so what are doing we're looking through each one of them and for each one we are adding a row to the table header so let's first take a look at what we have now so when you start typing okay so we have an issue data that for is not so this should be for each so let's try again let's reload here put an S and you see you get result right here when we are making an API call so when we get what a user has typed and then we are making an API call the problem is we are not clearing out the previous the previous data okay so when we get data basically we append it to try clip the element without getting the previous one so what we are going to first do now is here we make the API call we want to first clear out everything in the tip body for our results so we're gonna do in HTML and we set it to an empty string okay so once you get the data then we want to be appending the rule so here we can say plus equals in the theorem so for each of these zeroes we are going to be appending one by one to the T body depending on the results that we get okay so list it test it out sorry if I come and put insurance you can see that now it's filtered by insurance very search by test because that we get test by search by money and see that our results keep getting filtered by those money values so also if we say we search by like here like bro okay so you see we get the result and regardless so in Django use the I eye contains filter so you can see it can such everywhere regardless of a of the case of the strings which is pretty good and then we can even search by the dates so you can search by file like an expense we recorded on 600 v or forth so yeah now the sides now the search is working as you can
Info
Channel: Cryce Truly
Views: 7,801
Rating: undefined out of 5
Keywords:
Id: mBFqKPYrkJY
Channel Id: undefined
Length: 37min 16sec (2236 seconds)
Published: Sat Jun 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.