Django Channels Beginner Tutorial - Building a Basic Django Channels 3 App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone in this video we will build probably the most basic django channels example project possible there was some of you asking about adding django channels tutorials or adding channels to the social media app but before jumping into some more advanced products like that i want to make a video going over some basics of channels help make those more advanced projects easier to follow along and easier to understand so in this video we'll build a simple app that counts from one to zero automatically updates the page without refreshing and then once it's 10 i'll go ahead and just restart back to one and keep going like that we'll need to change a lot from our standard project so there'll be lots of new ideas and and different concepts in this so let's go to get started building this project so first thing we do open up a terminal and we're going to go ahead and create a virtual environment so i already have virtual env installed so i'll use that virtually v env to create that virtual environment let me go ahead and activate it by using source environment activate and this will be different if you're on windows but for mac and any linux operating system this should work fine like that and that's going to install django so we'll do a pip install django and we're also going to install channels as well so we'll do a pip install dash u channels and now with that installed we should be ready to go so first we'll create a new project so we'll do django django dash admin and we'll do start project and we'll call this one just basic and there we go with that project created i'm going to clear the terminal make this less messy let's go in cd into basic and right here we have our manage.py we'll go ahead and we'll create an app so we'll do python3 manage.py start app and we'll call this one um i guess counter it's fine now let's go ahead and migrate the changes so python3 manage the py migrate and now we should be able to run the server and make sure everything's working fine so we're on server we'll jump into a browser here reel the page and there we go now we have our basic um initial django project running so first things first to set up and use channels channels jingle channels we need to make some changes so by default django uses this wsgi file to run the application but you also see here we have an asgi dot py file asgi is what they call the spiritual successor to wsgi and what these do is they create a python standard for compatibility between web servers and frameworks and applications but one thing that wsgi does not have that we have here in asgi is we have the ability to run asynchronous code so when we run django channels we want to be able to run it asynchronously instead of just synchronously how you would normally run a django application and because of that we need to go ahead and make some changes so we use this instead of the original one so instead of our settings.py here what we can do here is we can go ahead and copy this line and put it right below here and then change the w's to a's so asgi right there and then right here asgi and now jingle will run this in our server instead of this now with that added let's go ahead and add our apps to our installed apps so up here i'm going to go ahead and first add channels add a comma i'm also going to add the counter app that we we created as well i'm going to save both of those and now if we go ahead here to our server and we stop it just go ahead and rerun it you'll notice now it says starting asgi slash channels version 3.03 development server at localhost 8000. so now we are clearly running the other server instead so if you see this right here you know that everything is set up correctly and you're ready to run and write any channels code now this file here this asgi file is not set up how we want it yet we add some more config here four channels so let's go ahead and add that right now so the first thing you'll need to do is we import a couple things so below this django core we're gonna go ahead and do a from channels dot routing import something called protocol type router and what this will allow us to do is allow us to have multiple different protocols so it's been like the http protocol which is all we used before we also want to use web sockets as well and so this protocol will allow us to handle both of those on our web server so what we'll do here with this protocol type router is we'll find this application equals line and we're going to go ahead and move this student to a new line and this will equal an instance of the protocol type router and as an argument you pass in a dictionary here we can pass in different protocols we want to use so first we'll set up http and we'll set this the value of this to be the get ascii application right here so we'll go ahead and put this right there and put a comma right there and we'll come back later and we'll redo some of this or add a line to set up websockets but for now this is all we need so now with this setup we can go ahead and start building our application so the first step will be to build our regular django core files that we normally do we need a view a template and a url pattern to show the index page because right now all we're showing is this page here we don't want to show this so to get rid of that we can go ahead and jump into our counter app we'll go to our reviews first and we'll create a new view and this will be like our other projects we've done before so this should be pretty familiar if you've seen the other videos but what we'll do here is we'll go ahead first import our generic view so from django.views import view next we can go ahead and create a class i'm going to call this index i'll pass in view right there and we'll go ahead and add on the get method so we do a def get past itself and request now what we'll do here is we'll create a context and we'll put uh just i guess count so that equal to for now we'll set to hello world as an example and then we'll go ahead and render a template so we'll do return render and we'll render requests and we'll pass in counter slash index.html and we'll pass in our context as well go ahead and save that and that's all we need for our view all we want to do is just pass in something in our context called account and we want to render a template let's go ahead and create that template real quick so we'll go ahead inside our counter app we'll create a new folder and we'll call this folder templates inside templates we'll create a new folder and we'll call this one counter and this is just typical normal django file structure here for our templates so if you're familiar with that you should know what this is already we'll create a new file here and we'll save this as index.html and here we go ahead and create a new html file so i'm going to try this from scratch let's do doc type um html and we could use a base template but for this example there's really no reason to it's it's a very simple one page thing here so we'll just go ahead and just uh put it all within our index file create a head inside the head here we're going to put some meta tags i'm going to copy these over just kind of basic neural medic tags we'll have a template we'll paste that right there and all this code will be in the description if you want to go grab those as well let's go and add a title as well so we'll do a title and we'll put a real time django channels app i guess will work for this title and we're going to close off the head and open the body inside the body for now all we're going to put in here is an h1 we're given an id what's this id the number and inside of here we'll pass an account so right now this is a hello world but once we actually get the django channels code running this should eventually change to be the number that's currently on and will change every second when we update the number now we're going to close off the body tag and close off the html tag and that should be it for our basic templates go and save that now it's going to create a url pattern so what we'll do here is we'll go to our base or root urls right here reals.py we're going to go and import include and we're going to include another file for our app urls so do a path this will be just empty parentheses and we'll do include and in quotes we'll pass in counter dot urls we go and save that and now let's have our counter app here we can go ahead and create a new file we'll save this as urls.py we'll go ahead and import our from django imports or from django.urls imports path no path we'll do url patterns equals a array here and inside of here we'll go ahead and add a url pattern so do a path this will be our uh just our index page uh when you go to import index as well so we'll do from dot views import index and so what we're doing oops we're doing here is we're going to our counter views and we're grabbing the index and we can go and pass that in here in case you'll know this dot just means go to the current directory so in this case it just finds the one in the current directory which is right here and it can find this index view right here but back here let's go ahead now and use the index view so do index and since this is a class based view we need to do a dot as underscore view i'm going to give this a name equaling index go and save that and there are our url patterns and our view let's go ahead now and just reload this page and it looks like we might have an error somewhere um there we go you reset the server and there we go so now we have hello world showing up right here now the goal is to take this hello world replace it with a zero and then a one then two then a three every second until we hit 10 and have that count start over again so to do this we need to add some django channels code so in django channels they have some different terms and even though a lot of this is similar to how the core django structure is so instead of having urls.py we'll have what is called a routing.py and this will hold our websocket paths so let's go ahead and create that first so create a new file we're going to save this as routing.py so what we're going to do here is we want to create pretty much a url pattern but we want to create it for our websockets so we'll need to do is just import path like we normally do so from django.urls import pass now down here we can go ahead and create some new up nor some more url patterns so i'll just go ahead and do web sockets sockets url patterns equals a empty list right here and now inside this list here we'll create another path just like we do for a normal normal url pattern i'm gonna pass in ws slash counter with the trailing slash and then like we do for our normal urls we need to pass in some sort of view here uh but in django channels they call it consumers so we have routing which is the same as our urls and we have consumers which is the same as our views and right now we don't have a consumer made so i'm going to type in our consumer right now and we'll go ahead and create it in just a second so i'm type ws consumer and then since this is a consumer here we've got to put dot as underscore asgi with parentheses let's go and import that right now so we do from dot consumers import ws consumer now this file doesn't exist yet so let's go ahead and create that file now so instead of our counter app here we'll create a new file we'll save this as consumers.py and now we can create our consumer which is really just the same as a view so first we'll import json then we'll go ahead and import our from imports from time import from time import sleep and then we'll go ahead and from channels dot generic dot web socket import web socket consumer now it's going to create that consumer so we'll do a class ws consumer which is the same as what we put over here so we're creating all we're doing is creating this right now it's ws consumer create class ws consumer and we're going to inherit from this websocket consumer which is like a generic consumer pretty similar to our generic view that we used here it just gives us some functionality that we can override in this case we override the get method over at different methods here for our consumer so we'll pass that in here like we do for reviews we'll pass in web socket consumer and now inside of here we can go ahead and override a method so in our views we overwrite a git method but in this case we have different methods and the one we want to override right now so this is just a basic example we'll just override just the connect method so we'll do a def connect pass itself and i can go to write our code here what to do when we connect to this websocket so what we'll do first we'll do a self.accept just accept the connection and then we'll go ahead and put our logic for our counting so first we'll create a variable called count so they're equal to zero and then we'll do a four i in range and we'll do a range of i guess a thousand or this is just an example so we're going to keep a loop going just to make this easy to do for this basic example we'll check if the count is less than 10 if it is and all we're going to do is just increment it one and send that so we'll take the count we'll do a plus equals to add one to it plus equals one to add one to it i should say and then below that we'll do a self.send these are built in functions to this that we can call to either accept the connection send data to the front end or whatever else so the self.send will send some data for us and what we want to do here is we want to pass in json dot dump s and inside of here we'll go ahead and pass in a dictionary put message put a colon and we'll put counts so we're taking this count variable or passing in here so first would be one that'll be two then three and then four up until it hits uh 10 and once it's 10 it'll skip this and we'll go ahead and do our next thing but before we do that with one line i forgot to add here which is sleep so we want to add a one second pause for each number but back to this so if we go ahead and get to 10 then we'll jump down here in our else statement and we'll go ahead and set count equal to one and then send that value so self.send and once again at json.dump with it put s there and then we will go and pass in message colon and account and then once again we'll do a sleep of one so we're taking our value here and it will send one in this case here and then i'll jump back here it's less than one ten it is and then we just have two and we'll send two and then we'll send three etc until we hit 10 again and it starts over and that is it for our consumer so we go and save that file let's go and double check make sure everything's working just come here build the page and it looks like everything is so that's good and now we have our routing and our consumers set up we're almost ready to add the changes to the front end but there's one thing we need to do is we need to add some code back to our asgi.py file to handle these websockets so right now all we handled was http let's go ahead and handle adding web sockets as well so before we do anything else let's go and import a couple things from our routing we'll need to import url router and then from channels dot auth we need to import off middleware stack like that we also import our websocket url patterns so from channels dot routing import web sockets url patterns i believe that's how i s what i called it let's double check that instead of our routing.py it was websocket url patterns copy that come back over here just double check and we'll paste that right there okay so now we have those things imported let's go ahead and add a line for websocket so we can add another key here and it's just called just web socket and then we can go ahead and set this equal to off middleware stack inside of this in our game we can pass in as url router and then inside there we'll pass in our websocket url patterns so all this is really doing it's just some built-in code makes it easy is this will authenticate the user then we'll have our url router which will route the current request url pattern to the correct view from our websocket url patterns list and that should be it for that let's go ahead and save that double check again make sure everything's still working it looks like it's not let's stop the server and just try re-running it looks like there's an issue here or something oh i put from channels.routing that's not right it should be from counter.routing we want to go to our counter application and find the routing.py and this has our website url patterns let's go ahead and save that and we'll save this now let's go ahead and try rerunning that and see if it works yes there we go so now everything should be working you should be able to page and still work okay great now we have our application set up to handle websocket protocol requests we can go ahead and add some things to our front end so let's go ahead and jump into our index.html file and we could put this in a separate file but for this example just to make it easier i'm just going to add a script tag right here and put the code within the html if you wanted to you could create a static folder and set up our static urls like you know we normally do for django projects but for this example just keep easy i'm just going to put a script tag right here so create script tag closing script tag and put our code in the middle so first we do is create a new instance of a websocket so do a from a var socket equals new web socket and actually i'm gonna go ahead and just use uh es6 for this so we'll do just a const socket equals new websocket and we'll pass in a string and we'll pass in our websocket url request the cr or the euro path for the request so we'll do a wscon slash slash and pass in local posts colon 8000 and in our routing here we did ws slash counter so once again here we'll do ws slash counter and you also need to put in these trillion slashes just as just to make sure you have those there on both the uh routing right here trailing slash as well as in our template here make sure you have those trillion slashes there and you'll notice here that we put ws colon slash i said instead of http that's because we're using our websocket protocol instead http here so make sure that is set up there as well now we have a socket we can go ahead and we can do a socket dot on message equals a function and we'll pass in e for event and we'll go ahead and write some code here to handle when it receives a message so once it receives a message we're going to do a couple things we want to parse the json we're going to go ahead and log that to the console and we're also going to go ahead and set this number id the value of this field right here to be that number so what we can do here is we can do a let's we'll do a const data equals json.parse and we'll do e dot data and we're going to do a console.log data and we'll go ahead and finally now we have logged the console let's go ahead and change this value here to be that number so we'll go ahead and do a document dot query selector and we'll go ahead and pass in a string and we'll put the pound sign with number since we're using query selector we either put a pound or a period if we're using a class it'd be a period but in this case since it's an id here we want to go ahead and use a pound so we'll put a pound sign right there and then number and then at the end of this we'll put dot inner text to change the inner text of this element and we'll set that equal to data and we'll do dot message inside of our consumer here we pass in on a dictionary here with the key of message in the value of cal so we do the data dot message we're grabbing this key here and whatever it's set to in this case will be whatever number that we're on currently so that's why we put data message right there and that should be it for a code let's go ahead and save that or run our server and we'll try running this and you'll see here we it counts up to 10. let it go here for a second and now it starts over to one it keeps counting and we've jumped into our console here you'll see it's logging the message each time so that is it really for this this little simple application we just got a working django channels project you'll see here it's not reloading the page at all it's just updating automatically for us without us doing anything so this opens up a bunch of possibilities for future applications we could use but for this example that says this is all we're going to do just so we have a working project and hopefully this helped kind of build a basic understanding of how django channels works and how to set up a basic project i'd like to create more a lot more videos with this in the future so if you have any ideas on what we could use for this i have a couple but if you have any let me know and i'll try to see if i can make a video at some point about those different projects uh but yeah that's really it the code will be description below as well as a link to the written tutorial thank you for watching and i'll see you in the next video
Info
Channel: Legion Script
Views: 1,312
Rating: undefined out of 5
Keywords:
Id: jAjA0jnDGcE
Channel Id: undefined
Length: 25min 12sec (1512 seconds)
Published: Mon Jul 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.