Django live search using Javascript and Ajax

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome to the final video in the django and javascript tutorial series so today we are going to create a live search and i already created a video on this topic however that video was about django and javascript itself in this one we are going to include ajax so let's actually take a look at what we are going to build over here we have a form with a single input and let's type something we can search for games over here so i'm going to type p and we have the witcher gta 5 and gta san andreas and then i'm going to add h and we only see the witcher and then i'm going to add another h and we have no games found and maybe if i add a we see some games so gta 5 gta san andreas fifa 20 fifa 21 but then if i for example type fifa we only see fifa's and then if i add 21 we only see 21. if we click on fifa 21 we will be taken to the fifa 21 detail page and this is basically how this is working so yeah let's get started on this alright guys so before we get started with coding let's take a look at what have i done so far so i started a brand new project called search project and currently i'm in the settings py file of this directory so if we scroll down to the installed apps we will notice the first change i added games so this is the application that i started for this project purposes and here is the games folder and we will dive into it very soon let's scroll down to the templates over here we are telling django where we are going to keep additional ones and in our case this is going to be the place where we will store our base html files so the main template from which other templates will inherit and then if we scroll all the way down over here we have some settings for the static and media files and those settings have been included in the url patterns and yeah what do we have over here we are telling django in the static files here is where we are going to keep our static files so if we go to the static folder i already created main.js and style css and then in the media root we are telling django where do we want to upload the media files and in our case over here we are going to store images representing the games so we also have a media folder already created in the base directory and here all the images will be uploaded and stored all right so now let's go to the static folder let's take a look at the main js over here we just have a simple console log with the hello world and then if we go to the style css we have some classes created and i tried to use bootstrap as much as possible possible however those classes will be helpful in some situations so we will use them a little bit later on and we will return to this file okay so right now what we need to do is to jump into base html and over here we have git bootstrap css in the head we have jquery because we will be using the jquery ajax method we have custom css njs so over here we created our first block and we named it scripts and here we will provide a script for the template that actually meets the script so in our case this is going to be the main html file and we will link in the main html file this main.js file that you see in the static directory in terms of all the templates they will have this style css linked up okay it's already done over here so in the base html file we already have the style css linked up and each template that will inherit from base html will have this style css available okay and then if we scroll down we have a title i just placed over here search for games i didn't add any blog title but feel free to do so if you want and then in the body we have a div class container with the margin top three and then we have the block content okay and then we also have getbootstrap.js bundle so we are using bootstrap version 5. all right guys so i think this is it and i think we are ready to get started so let's jump into games and let's open up modals py file here let's create a class which we are going to name game and this class will inherit from models.modal we will define three fields the first one is going to be name and this is going to be a model's char field jar filled with the max length and let's set it to 200 okay then we will have the studio so who created this game i'm just going to copy this field with the name and here i'm just going to change the name to studio all right and then let's also have image and this is going to be a model's image field with the upload 2 and let's put in images okay so inside the media folder we will have another folder called images and over there we are going to store the images that we are going to upload all right so let's take care of the string representation method in a second we will install pillow because we are using image field so we will return to this in a few seconds but for now let's take care of this string representation method and let's return just str self name okay so i'm going to save this and i'm going to register um this class in the django administration so we need to go to the admin and here from dot models we want to import game and then admin site register and we need to pass in the game so let's save this and let's go back and over here we already see a hint that pillow is required so let's quit the development server from running and um yeah i didn't mention it but i already created a super user i already have everything set up except of course the main page but you already see the django administration i'm already logged in and yeah it's pretty cool that it actually has a dark theme we will return to this in just a second for now we have quit the development server so let's install pillow pip install pillow all right and let's run the migration so python manage py make my creations and python manage py migrate and python manage py run server all right so um the django administration has now the dark theme and i think this is because i have a dark theme set up on my operating system so if i'll change it to light i think this should change as well so let's try it out i'm going to select light and yeah it changes okay and then i will i don't know how this works on windows um but yeah this is something new i think to django 3.2 to be honest i didn't look up yet what are the features the new features new releases new changes in the django 3.2 um i'll do that when i have a little bit more time for now let's hit refresh and we have games over here so as the next step i have a special task for you please prepare some game images so i already done this i have a games images folder and i have here cyberpunk fifa 20 fifa 21 gta san andreas gta 5 and the witcher okay and these are the games that i'm going to upload by adding them from over here so i'm going to press add and i'm going to put in cyber punk this is going to be cd project red and then i'm going to select an image so let's go to um where is game images and cyberpunk let's press save and here is the cyberpunk object all right so i'll do the same with the rest of videos i'll pause the video right now and we will see each other in a few seconds all right guys welcome back so i created those objects that you see over here fifa 21 fifa 20 gta san andreas gta 5 the witcher and cyberpunk so let's go back to our visual studio code and right now what i'm going to do is to jump to the views py file of the games application so here we will need a few views actually three views right so the first one is going to be domain view and this will take in a request and i'm just going to write pass for now then we will need the game detail view so once we find the game and we'll click on it we will be taken to the detail page all right so this will take in a request and primary key and for now i'm also going to write pass and finally we'll need the logic and a view that will return a json response so it will handle the logic of searching for a game and it will return a json response with the results found or if there aren't any results we will get a message that none of the games has been found alright so i'm just going to name this view search results and this will take a request and let's put in pass okay so let's focus on the main view first what i'm going to do is to return render and then let's pass in the request and we need to provide an information over here which template is this view referring to so we are going to go to the games application and over here we are going to create a templates folder inside let's add another one called games and let's put in main html okay so this main html will inherit from base html we'll need to load static because we'll need to link up our script our main.js okay so we will do this in the block scripts so for now i'm just going to leave it empty and then we will have a block content and here i'm just going to put in hello world for now okay so let's save this let's go back to the views py file and let's provide the path to this template over here so it's going to be games slash main html and then let's add an empty dictionary because we aren't passing anything to the template all right so let's go ahead and save this views py file and then we need to create a urls py file in the games application folder so let's do this very quickly urls py all right and here let's go to some imports from django urls we want to import path and then let's bring in the views so from dot views we want to import our main view our game detail view and also our search results view all right i'm going to set the app name to games and then i'm going to open up the url patterns list and here for now of course i'm just going to register the main view which is going to be as the name suggests the main view so path and then this is going to be empty because as mentioned before this is going to be our main view so let's pass in the view itself and the name let's set to main all right so let's save this and right now we actually need to go to our search project to the urls py file and here we need to include the url patterns defined in the games application in the main url patterns so in the main urls py file so let's do this very quickly let's write path and here i'm just going to write include so actually i need to import include first include okay and then we want to go to games and then urls let's add a namespace and let's put in games all right so let's go ahead and save this and then right now we shouldn't have this page not found anymore once we refresh the page okay we have hello world all right so everything is working however if we right click inspect and if we go to the console we don't see hello world first of all let me make this a little bit bigger and then let's focus on this problem because we don't see hello world and this is because of the fact that we didn't link up the scripts okay so we need to do it right now so in the blog scripts let's put in script and then src is equal to and then let's put in static static all right and then we need to refer to the main js okay and we can close off the percent with the curly bracelets let's add defer and let's close up the script all right so this now should be working i'm going to save the main html i'm going to hit refresh and we have hello world all right so as the next step let's actually add a form over here okay so in order to do this we need to work a little bit more on our block content so instead of hello world we are going to have a div with a class equal to let's say w100 and this is a bootstrap class i'm going to put in text center and i'm going to close up this div so inside of this div we are going to create a form and i'm going to set an id of search form and i'm also going to set autocomplete is equal to off so we won't see the history of our search results and then i'm going to close up the form over here and then let's put in the csrf token and let's create an input this is going to be a type text let's add an id let's maybe name the search input like this and over here we need to define some classes so first of all i'm going to add a padding 3 the width will be 50 and i'm going to use a custom class that i created in the style css search okay so if we go to style css we have search focus so if we click on this input the background color will change all right so let's go back to main html let's close up the input over here or maybe let's also add a placeholder and the placeholder will be search for games and then in example the witcher all right and yeah let's save this and let's see how this looks like so i'm going to hit refresh and there it is okay so this is a little bit maybe too big all right so maybe maybe i'm going to just change the padding maybe padding one will be enough okay and then i'm going to make this just a little bit bigger search for games okay and as you can see on focus the background color changes okay so as the next step let's return to our main html and here i'm going to add another div and i'm going to set an id of results box and yeah inside of this div i'm going to add a class and we are going to refer to the results card so again let's go to style css over here we have the results card defined we have the width max height the box shadow transition border radius and padding okay so now that i think about this we actually can remove this max height and yeah this is the results card and we also are using not visible so basically this div won't be visible for now at least okay we have a display none alright so i think we are done with the main html let's go back and let's see what do we have yeah i think i think we are done so um i'm going to actually put something inside okay we didn't close up the div and i'm going to put in test and as mentioned before we are going to be using the not visible class but for now let's just keep it as it is and i'm going to press enter and we have this um results box over here so it's not centered and yet the easiest way i think to put it in the center is by adding a style and i'm just going to put in margin or we can do it we can do it directly in the results card so let's save this and let's go to the style css and here let's put in margin and then over here let's put in zero auto all right so let's save this and let's refresh and there it is okay so initially this results box shouldn't be visible so let's go to the main html let's get rid of test and let's add not visible class not visible like that visible all right let's save this let's refresh one more time and maybe let's clear the cache command shift r okay so the not visible didn't work results box not visible okay and this is because i've placed it in the id and it should be of course in the class so results card and not visible let's save this again sorry about this guys let's hit refresh and now it's gone okay as the next step let's go to our main.js and let's grab all the elements from main html okay so we need the search form we need the search input we also need the csrf token we need the results box and yeah probably that is it and we will also need the url okay so actually we can begin from the url so in the main.js let's define a const const url and this is going to be window location ref and let's console log the url right now okay so let's save this let's hit refresh okay it didn't work so i'm going to clear the cache command shift r and over here we have the url so basically this matches this okay so as the next step let's add the search form and the search input so i'm going to put in const search form and this is going to be document get element by id and i'm going to put in search form as we did in the id of the form okay so in the main html we have a form with an id search form and this is how we are grabbing this element by this id okay so this is a search form and let's do another one for the search input search input is equal to and then again document get element by id search input okay so we have an id search input and this is how we are grabbing this input so if we now console.log search form let's save this we will have a form and then if we put in search input let's save this and let's refresh we will have the input perfect so uh there's one thing missing actually two things missing we need the results box and we also need the csrf token so let's do first the results box results box is equal to and then i'm just going to copy this paste it and here let's put in results box all right and then we will have a cons csrf and this is going to be a little bit different so we need to put in document then get elements by name and we need to put in csrf middleware token all right so let's console.log csrf let's take a look at what do we have over here okay we have a node list and if we scroll all the way down to the value here is our token okay so this is basically our token over here so what i'm going to do is to simply go back and access this uh token so we need to put in 0 and then dot value and now let's save this did i spell this correctly i think so let's hit refresh and here is our token all right so as the next step we can actually refer to the search input and in order to have a live search with ajax we are going to use a key up event so let's take a look at how this will work i'm going to write down search input and then add event listener and here i'm going to pass in the key up event and then we will have this event and we can simply console.log e target value all right so let's see what this will give us let's save the main.js let's return to the browser let's hit refresh and let's type something h and we see h h a okay so everything is working let's write hello and as you can see over here we have hello so uh yeah this is how this is working okay so on the key up we have a target value every time updated so we can actually see in the console what we are typing in the input all right so as the next step let's actually remove this not visible class on the results box okay so we will do this in this search input ad event listener block and we will do is do this only if the results block consists of this not visible class so we need to write an if check if results box class list and then contains and we want to put in not visible and if this is the case what we are going to do is to simply re remove this not visible class so we need to again refer to the results box class list and then let's put in remove not visible okay so let's save this and as you can see right now we see it okay so if we refresh it again we start typing we see this okay so this is working and now we are going to focus on a function that we are going to create and we are going to call this function in this block and this function will be named send search um maybe send search data something like this and we will pass in this event target value all right so right now we need to create this send search data which will take something in it will take in some text some game text all right and let's do this so i'm going to define it above the search input below the csrf we can actually get rid of this console.log csrf and maybe somewhere over here let's work on this function so i'm going to uh create it as an arrow function and as mentioned before this will take something in okay here we are passing the event target value so we are passing some uh text some keys related to the game name so here i'm just going to put in game all right and inside we are going to open the jquery ajax method we need to define a couple of things so the first to define is the type we are going to work with the post and then the url is going to be blank for now okay and the data we will send the csrf middleware token so csrf middle where token and to the csrf middleware token we are going to assign our csrf variable over here and then we will set again and this is going to be the key which we will pick up in the views py file and to this key we are going to assay assign the game from over here and as a reminder this is the event target value all right so and then as the next step we need to define what will happen on success success so here we can have a function or we can also have an arrow function and this success will take in a response so i'm just going to put in res as a shortcut and let's put in console log rest okay and in case of an error we will also have an arrow function that will take in an error and let's just console log the error all right so right now we need to work on the url we will focus on the success block so we can actually see a response but first of all we need to create a view which will return a json response so we can see it over here and this view needs to be registered so we can actually provide the url all right so what i'm going to do is to jump into the game's views py file but first i'm going to save the main.js and we'll need to work this time on the search results so instead of pass what i'm going to do is to make an if check if request is ajax all right then what we are going to do is to get the game so game is going to be request post get and we want to get it by the game key this is what we've set in the main js and then let's print the game itself over here and let's also return a json response so we need to go to django http and from here let's import the json response so let's return json response and let's have a key data and to this data key let's for now assign game all right so let's also return an empty json response if this condition isn't met okay so here let's just put in empty json response we're not going to worry about this scenario okay let's focus on this part i'm going to save the views py file and i'm going to go to urls and right now we are going to register the search results it actually now returns something okay so i'm just going to copy this put it below and let's put in search and let's put in search results and the name is going to be search so i'm going to save the urls py file and we need to return to the main.js and now we can put in search this is the url okay so let's save this let's hit refresh and let's see if this will work okay so we have a json response over here and again and again and again okay so this is the json response that we've set in the view and over here we have the game printed all right so let's again go to the views py file here we are printing the game and here it is all right and then we are setting return json response and as the data we are setting the game and we have it also here is the event target value e target value okay and here is the json response with the data key and the game so hopefully this is understandable so let's do a little bit more in the search results first of all what i'm going to do is to define a query set based on this game all right so let's write qs is equal to game objects and then filter and we need to refer to our name field okay so let's write uh over here inside name and then double underscore i contains and whatever uh the game is so we are assigning the game with the name i contains okay so um right now this shouldn't be case sensitive it doesn't matter if we write it as small or big letters and this should actually give us some results so let's print the qs right now okay so i'm going to save this and i'm going to hit refresh and then i'm going to start typing v and we have an internal server error so let's see what do we have okay game is not defined makes sense we didn't import the game so from dot models we want to import game let's save this let's hit refresh and okay so right now we see the data however what's interesting for us is this qs so as you can see we have only one result the witcher okay and notice that i typed this with a small letter and uh we have the result anyways okay and this is because of this i contains okay so let's maybe type fifa and what do we have over here and we have fifa 20 and fifa 21 perfect okay so we need to obviously continue working on this logic let me just get rid of this print qs and print game okay so as the next step we are going to write an if check a double if check so if length qs is greater than zero and the length of the game is greater than zero [Music] what we are going to do is to open an empty data list and as the next step we are going to loop through the query set so we can't pass the query set directly because we will have an error that the game object isn't serializable something like this okay so instead what we are going to do is to create an item in each iteration of this query set so i'm going to put in for pause in qs and here i'm going to create this item dictionary and i'm going to set a couple of fields so the primary key is going to be the position primary key all right then i'm going to pick up the name and this is going to be the position dot name then let's also add the studio okay so i'm referring to the fields of the game model okay the game class and here we will have the position studio okay and with the image we are going to put in str and then position image url okay and finally what we need to do is to write data append and we want to pass in this item so for every position we are going to create this item and then we are going to add it to the data list okay all right so as the next step let's actually do an else for this if check so here we will have an else and for now i'm going to put in pass because initially i'm going to set a variable res to none and if this is the case over here if lame qs is greater than zero and the length of the game is greater than zero what i'm going to do is to simply set rest to data okay and in other case i'm just going to put set rest to something like um no games found all right and then instead of returning the json response with the data key game all right as the value as the value now we are going to pass res so to the data key we are now assigning rest so let's save this and let's see if this will work or not okay we have an array over here and what do we have inside of this array gta and fifa's okay and this makes sense because those games consist of um the a letter okay so what i'm going to change over here is the fact that now we want to display not res but we want to access the data so i'm going to put in rest data and let's hit refresh a and it didn't work so let me check if i save this yes i'm going to clear the cache okay let's see now and there it is okay so right now we have directly in the array and here are the results okay so if i type a again we have no games found no games found and then if i put in v okay so here we have uh the results that consist of the t letter but then if i add h we have only one results and this is the witcher okay so this is working and this means that we are i think we are done with the uspy file at least for now because we will have to return to the game detail view but for now um i think we can focus again on the main.js and to be more precise we need to focus on this success block so what i'm going to do is to define a cons data and this is going to be equal res data and now we need to check if we are dealing with an array okay because if we take a look at uh the response that we get we we get either an array or a string and we want to continue with the logic for displaying the games over here only if we are dealing with an array so what i'm going to do is to write an if check and here i'm going to write array and then is array and i'm going to pass in the data okay and if this is the case we are going to work on the logic so i can for now console log we have an array all right and then in other case what we can do directly is to do first of all a check if and then search input value and then length length [Music] is greater than zero okay so if we actually have something written down over here because we can actually delete this okay so if if we have something in the search input what we are going to do is to go to the results box in our html and we are going to maybe use backticks and in bolded font we are going to display the data okay so the data in this case um maybe this isn't a proper uh name because the data is a good name for this block okay for for this isn't this this data isn't that good because we don't have basically any data of uh of our game objects we just have a response that there is no no games matching so let's save this and let's see how this will work okay we have an array so this block was successful and then we have no games found all right and then if we delete this we still see no games found so we need to do some additional logic provide some additional logic in the success block in the else and [Music] create simply another else for this condition so if the search input value length isn't greater than zero so if it's uh if it is actually zero so this is what we are defining over here else means basically that the search input value length is zero and as mentioned before this basically means that the search input is empty so here we are going to write results box and then class list add and we are going to add not visible all right so let's see how this works right now i'm going to save this hit refresh okay and there it is so now let's focus on this part so i'm going to get rid of this console log and instead i'm going to put in data and we are going to loop through the data with the for each so at this point we know we are dealing with an array so we can grab a single game and we can refer to the results box and we can simply add the results that are inside of the data so i'm going to use again backtext and here i'm going to begin with an ahref for now i'm going to leave it empty and then let's close it off over here okay and let's add a class over here to item so if we go to style css over here is the item and it basically says that we shouldn't have any text decoration all right so let's go back to the main.js and as the next step let's add a div with a class equal to row and maybe let's add some margin top two and margin bottom two like this okay and let's close up the div over here okay so inside of this row we are going to add some columns so first of all i'm going to put in div class call 2 and this is going to be for the image and then i'm going to copy this and here we will have 10 and this is going to be for the name so as a reminder bootstrap uses 12 grid system and 2 plus 10 in one single row it's equal to 12 okay so let's go over here and let's provide the image so emg src and this is going to be equal to and then we need to refer to the game image like this okay so dollar sign curly bracelets game image and remember to use backticks all right and then let's put in class is equal to game emg like this all right so let's go again to style css and here is game emg with 50 pixels height 50 pixels and we have a border radius we will see if this border radius um will be necessary or not for now let's just keep it and let's return to the main.js so here we have uh this class and i think right now we can focus on the second div with the class call 10 and here we want to display maybe in h5 h5 let's display here the game name game name like this and then let's add a paragraph with a class equal to text muted so again this is a bootstrap class and let's close up the p and here we will display the studio so game dot studio all right and yeah let's see if this is working or not i'm going to save this going to hit refresh and let's see okay so we have a problem over here um assignment to constant variable and this is it so sorry about this stupid mistake it should be results box inner html so again let's hit refresh and let's start typing and there we have the results okay so the problem is now that they are duplicating and we actually don't see the image so over here we have the game image and i think i forgot to close up this game image okay with a quotation mark so this might be the problem and in order to not duplicate the results we are going to grab this results box in our html and we are going to go to this if array is array data and above the for loop we are going to simply set it to blank and let's try it out one more time let's type a and here we have the results and then maybe let's add another a and we have no games found okay i've deleted it we don't see any uh results box and then if i type d we have three positions the witcher is the only one that consists of the the all right so this is basically working let's try it out one more time okay yep it seems to work however we aren't able to go to the correct page if we click on it we are just taken to the same page nothing happens so what we need to do is to create very quickly a detail page so in order to do this i'm going to go to the templates of the games application and here i'm going to create another one called detail and let's write detail html which inherits from base html we won't need any static block or we won't need the block scripts we just need block content and now let's save this and let's go to the views py file and let's finish this particular view so first of all let's create let's get actually the object based on the primary key so this is going to be game objects get pk or let's do it a little bit in a different way so from django shortcuts let's import git object or 404 so here let's put in git object or 404 let's pass in the game and set the primary key to primary key just like this okay and then let's return render we need to pass in the request the path to the template so games and then detail html and this time we will pass the object to the template so here i'm going to set the key obj and to this key obj i'm going to assign this obj value this variable over here okay so right now we can actually save this and as the next step we just need to put this obj name inside of the detail html so in the block content let's add a h3 maybe and over here let's put in obj.name all right so let's save this and now we need to go to the main.js and refer to this href so we need to put in the url all right and then we need to refer to the game pk so i'm just going to copy this and put it next to the url so here instead of the game image we will have game primary key because if we take a look at the views py file we also set the pk key over here so we can do this let's save it and actually in order for this to work we still need to register the view the detail view we forgot about this so i'm going to copy this line of code and then i'm just going to paste it here we will have the primary key and we will have the game detail view and i'll set the name as detail let's save this let's hit refresh and let's try to click on the gta 5 and we are taken to the gta 5 page so everything is working and yeah i think we can finish off over here i hope you guys enjoyed this tutorial and hopefully we will see each other in the next one so i think this was the last video in this django and javascript tutorial series at least for some time but uh yeah pretty cool content is coming up so if you haven't subscribed to the channel please do so if you love python please subscribe and we will see each other in the next one have a great day and bye bye
Info
Channel: Pyplane
Views: 4,552
Rating: undefined out of 5
Keywords: django live search, django and javascript, django and js, django javascript, django js, live search in django, live search django javascript, python django search form, django with js, django with javascript, django javascript integration, django 3 tutorial 2020, learn django with js, Python django javascript, django ajax tutorial, django ajax get data from database, django ajax search, django javascript project, django javascript tutorial
Id: dIcCi2SG1CU
Channel Id: undefined
Length: 56min 34sec (3394 seconds)
Published: Tue Apr 20 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.