Python Django Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] this video is sponsored by dev Mountain if you're interested in learning web development iOS or UX design dev Mountain is a 12-week design and development boot camp intended to get you a full-time position in the industry to learn more visit dev mountain comm or click the link in the description below hey what's going on guys welcome to my django crash course so I did a crash course on Django about two years ago but it was versioned one of the framework and we've been in version 2 for a while now and I've gotten a lot of requests to to redo this so we're gonna build an entirely new application we're gonna build a polling app that is similar to the one that's in the documentation here at Django project comm so there's a tutorial if you go down here too it's actually a seven part tutorial so what I'm gonna do is build something very similar to this but really slim it down so that you can understand it better because as you can see there's just a ton here and this is just part one so then you go to part two and it's just it's a lot so I'm gonna try to simplify it and help you understand it better we're also going to add a couple things to it like like like bootstrap UI and a landing page and stuff like that so this is what we'll build and this is just the simple landing page so we can view available polls and you can see we have some questions here so what is your favorite programming language your favorite JavaScript framework Python framework if we click vote we can go to that specific poll and we can go ahead and make a choice and vote and it's going to take us to the results for that particular poll so you can see Django has 12 votes flask 5 and web 2 pi has 3 so we could vote again or we could go and vote in another poll and then in addition to that we have an admin area so if we go to slash admin we can log in here and from here we can create groups and we can manage our users you can see I only have one user which is the admin user and we can also manage our questions or our polls so here you can see all the different polls we can add a new one so we can put the question here and then all the choices we can add more choices so quite a bit of functionality for the amount of code that we're going to write that's one thing that's great about Django is it's very high level and even though you have to do things the the Django way it gives you a lot of features right out of the box so of course we can edit the question and we can you know add and remove choices as well and that will show up in the front-facing website just right here alright so that's what we'll be building so let's get into it you're going to need to have Python 3 installed right now you can see at Python org the latest version is 3.7 4 so just get that installed I'm not going to go over that and you can you can do this on Mac Windows Linux doesn't matter as long as you have Python installed and I'm gonna open up vs code that's what I'm gonna use for my text editor and I have just an empty folder called pollster project and I'm gonna go ahead and open up my integrated terminal here now once you install python you'll have pip which is the package manager for python and you could do pip install django like that but that's going to install it globally on your system and you probably don't want to do that you want to set up a virtual environment for each project that you create on your system and any Python project so we're going to use something called pip env to do that so what you want to do is pip install pip env okay I already have it installed so I'm not going to run that but once you do that you can just say pip env shell and that's going to create a virtual virtual environment so you can see it's going to be in this location right here and then any packages we install including Django will go into this virtual environment rather than our global system and it also created a pip file which will list any packages that we install ok so let's go ahead and clear this up and let's do pip env install Jango okay so this should install Jango which should show up here under packages ok so there it is good and that's that's all we need really we're going to use the SQLite database that is the default for Jango if you want to use Postgres or MySQL you can you just need to simply change the settings in the in the settings file which I'll show you in a little bit so let's see we have Jango installed so now we should be able to say Jango - admin and I'll probably create a gist file for you guys that has all the commands so you don't you know so you have it all in one place but we can say Django admin start project and then I'm gonna call this pollster alright so we'll run that so up here you can see it created a folder called Polestar now before we look at that I just want to explain the concept of a project and apps so with Django your project is your basically your overall website your overall application and then you have a concept of apps which you can have multiple apps within your project usually you do so let's say you have a blog you'd have a blog app if you wanted an e-commerce shop you probably have a shop app what we're gonna have is a pulls app and that's gonna have everything to do with the polls and the choices and then we'll also have a Pages app just so we can have some static pages so we can create the landing page and so on alright so let's look in this pollster folder and there's two things here there's another folder called pollster and then there's a manage dot pie file so this manage dot pie file we don't we don't touch this at all as far as the code but we use it all the time it's basically the command line tool for Django so we want a CD into pollster and if we do an LS we should see that manage pie okay that's what we use to run the server to create migrations and all that stuff and then if we look in the pollster folder a second one here the inner one there's an init dot pi which we don't need to touch at all it's blank anyways settings dot PI is our settings file so this is where we put things like our base directory our secret key for production any installed apps now Django like I said it's very high-level it comes with a lot of stuff and it comes with all these apps so admin which handles the admin side authentication sessions messages all this stuff comes with a bunch of middleware as well and we have some template options and then here is where you define your database okay so we're just going to use SQLite 3 which is the default but you could just change this to post grass or PostgreSQL and then you could add the username and password and you could say and you could use postgrads alright so let's see off passwords validations language code so some date and time stuff static URL and there's other stuff you can put in here as well so that's that's the settings file and we have the URL spy file which is basically our routes and each app that we create such as the polls app will have its own URL spy file and then we basically need to import that into here and set URLs like we're gonna want polls slash whatever to go to our polls app okay they already have the admin one here for us so I'm just gonna close that and then we also have this WSGI file which just has to do with our with serving our application we don't need to touch that at all alright so that's the kind of the core files that that's that are created when you create a project now before we create our polls app let's just run the server so we're in the same folder as manage dot pi so we can say python pi run server now if I just run this it's gonna run on port 8000 which is fine but I already have something running on 8,000 so I'm gonna specify a different port say 80 81 alright so the server's running as you can see and we're gonna get this message saying we have unapplied migrations and what this means is that there's migrations that are ready to create database tables like the admin table auth content type sessions as you can see here and those haven't been applied and to apply them we simply run managed by migrate alright so they're basically the default tables that are needed for that for a boilerplate django app and we can create our own migrations as well which we're gonna do in a little bit so if we visit this URL we're gonna see the just the django landing page alright so i'm gonna go ahead and stop the server and let's run those migrations so as you can see right here it just says we need to run manage dot pi migrate so let's clear this up and let's say python managed dot pi migrate and you can see everything went okay so now we have all those tables in our database now we're using SQL Lite so there's not there's not really a way I can show you the tables if you're using Postgres you could use PG admin or if you're using MySQL you could use something like PHP myadmin and you would see the the you know the admin table and stuff like that alright so now that we've done that let's create our first app which is going to be our polls app so to do that we do Python manage dot pi and then start app okay so whenever we want to create an app with for our project we use start app and we're going to call it polls ok now whenever you create an app it's going to come with a set of files as you can see here so we have migrations which is a folder for any migrations and we're gonna create one a little bit and a knit dot pi and admin dot pi so if we want to add polls or questions to the admin area we need to add some code to this file which we'll do later app spy which has a class of polls config which we're not going to touch and then models this is where we create our database models so basically we're gonna have a question model which which will refer to a question table in the database and also a choice model which will refer to a choice table in the database and they're they're both going to be related to each other because obviously questions need choices we have a test stop pi for running tests which we're not going to get into in this video and then views which can render templates basically we can connect views to URLs and we can either render a server-side template or we can render Jason if we're creating like a REST API or something like that and by the way do have a series showing you how to create a pretty in-depth REST API with GWT authentication in Django I have a series on YouTube where we do that and then we add a react front-end and I also have a course on udemy a django course as well where we build a real estate app and I'll put links to those in the description ok so we have our app here our polls app so the next thing that we're gonna do is add the models so let's go to models dot pi and in here we're importing basically the base model class that we want to extend we want our models to extend so down here let's add a class of questions so basically any model you create is going to be a class and it's going to extend modeled or models dot capital M model okay so it'll it'll basically inherit all the methods from it and then we just need to specify our fields so we're gonna have a question underscore text and these are the same fields that are in the documentation tutorial so you can always refer to that you know the docs as well so we want to set this to a certain type so this models object here has our instance has a bunch of fields we can use different types so this is going to be a character field or char field and we can add in a max length here and let's do 200 okay and I should mention that it'll also create an ID automatically which will be our primary key and it should be auto increment by the by default so we're also going to have a publish date pub date set that to models dot and this is going to be a date/time field we can put some text in here that can be displayed so I'll say date published that and let's create another class called choice okay so this is our choice model this is also going to extend model dot all the way around models dot model and then this will have an ID of course that'll be a primary key now we want to create a relationship between choices and questions so let's have a question field and the type is going to be a foreign key okay because basically we want to we want to link this foreign key to this to the primary key of the question table so we need to define the question model here and then I'm also going to add an option of on delete so basically what happens when a question is deleted because these are going to be related and I'm gonna say models dot cascade and what this means is if there's a question that's deleted all of its choices will also be deleted because we don't want choices just hanging around if it's as if there's no question and the database for those choices okay so we also want of course the text choice text so models dots it's going to be a char field and we'll do max length 200 and then we're also going to have votes okay so votes is going to be an integer so integer field and we're gonna actually have a default of 0 all right so those are all the fields not as not many now when we add questions and choices in the admin area it's if we leave it like this it's just it's basically just gonna say question object and it's gonna look kind of weird and what we want to display is the question text and the choice text for choices so we can actually do this define string double underscore STR double underscore which takes in self so basically the the instance or the class and return self dot and then whatever field we want to use which we're going to use question text okay so we want to make sure we add that and we'll do the same for choice text for the choice model and make sure your indentation is correct so this will be a choice text alright so I'll save that you might get this pop-up here for auto pep eight basically it's a code formatter if you're using vs code I would suggest doing can you might have some issues if you don't select the correct Python interpreter so I'm going to do ctrl shift P or command shift P and just type in Python and then select interpreter and make sure this is selected this pollster project Pippi and V okay and then I'll just say yes to this I guess it might ask me to install pilant as well which is a linter okay so let's see let's make sure we save this this models file now I want to I want to start to add some data and we can do that through the shell before we get into like creating you know the user interface to add a question or you know the admin area or whatever we can do that through the shell and I'm going to show you how to do that so you technically don't have to do this part but I want to show you anyways so we can do Python actually I think we're still in the right place no for some reason it knocked us out of the pollster folder so I'm going to CD back into pollster and we need to create a migration okay we have the models file that we created with the fields but we don't have the database tables set up yet so we have to do that but before we do that we need to go to our settings file so pollster settings dot pi and this installed apps right here we actually need to add our polls we need to save polls dot apps dot polls config and the comma and this actually refers to our polls apps dot pi file right here you can see and then we have the polls config class that's what we're we're basically just adding that to the current apps in our application our project alright so now let's create the migration so clear that out and let's say to create the migration we're gonna say Python manage dot pi make migrations polls all right so down here you can see that it actually created a migration file called zero zero one initial dot PI and we can check that out up here and if we take a look at it and we just make this smaller it's basically a file that's gonna tell the database what to do it's gonna create a table called questions it's gonna have an ID that's going to be the primary key it's gonna have a question text a publish date we're gonna have a choice or choices table with an ID we're gonna have a foreign key field for the question votes and choice text okay now so we still have we still don't have this in the database we just simply created the file in order to to actually run the migration we're gonna do what we did before which is managed PI migrate so now those tables should be in the database alright now we have the tables in the database we could start to work on our views and stuff like that but I'm actually going to show you how we can manipulate the data from within the shell so if I do Python not Python dog manage dot pi shell we're now in an interactive shell where we can have act we can get access to the models into the data so I want to go ahead and insert a question and just show you that we can do some queries and stuff here so first thing we'll do is bring in the models so from the polls app dot models we want to import the question and the choice models okay once we do that we can actually make queries we can take the question model and we can do objects dot all and this is all in the documentation it's all in the tutorial if you want to use that as a supplement and you can see we our query set is empty right and of course is we have an entity we haven't added any questions so what I'm going to do is actually add a question I'm going to create a variable called queue set it to question and then the field question text came in we have that char field and I'm gonna set that to what is your favorites Python framework frame walk framework alright so that's the question text and then let's do the pub date and we'll set that to actually you know what we have to bring in the time zone package so let's actually get rid of that because we need to bring in the time zone package from something called Django utils so from Django dot utils import time zone okay and then we'll do Q equals question put in our question text which is what is your favorite Python framework and then pub date so pub date we're gonna set that to time zone we're gonna use that package we've just brought in dot now which is a method that we'll just put the current date and time okay so what we did is we put that into a variable called queue it's not in the database just yet we have to save it so let's do Q dot save and now if I do Q dot and then one of the fields like ID it should give it to me so Q dot question underscore text and we get the question text all right so let's clear this up and we're still gonna we're still in the shell and what I want to do now is I want to add some choices to that question right in fact let me just do a quick query so if I do question dot objects dot all now you can see I have one question in my query set okay that's in our database and then we can filter so we can do question dot objects instead of all we can do filter and we can filter or we can say where ID equals one and that will give me the the question with the ID of one we can also do instead of filter we can do dot get and we can say where the PK where the primary key is equal to one okay so that's actually going to give us just the question all right yeah this will filter this will give us basically a list or an array and then this will give us just the single question so let's see let's um since we have choices relate that are related to the choices table is related to the questions table we can we should be able to say Q actually let's set Q equal to question dot get dot or not question docket objects get primary key equals one so what that did is it just put this into this variable so if I want to see the choices we can actually do Q dot choice underscore set dot all and you can see we have no choices for that question so I'm going to create some choices I'm gonna say Q dot choice underscore set dot create okay so when we use the create method and then remember we have a choice text field and I'm gonna set this first one to Django and I'm gonna set the votes field to zero okay and I'm gonna do the same thing but I'm gonna choose flask or add flask as a choice and then I'm gonna add web to PI as a choice okay so now if we do this Q dot choice set dot all you can see all of our choices so we now have in our database we have this question what is your favorite Python framework along with these choices associated with it okay so I'm going to go ahead and quit out of this and okay so everything looks good alright so it should have one question with three choices in our database so now what we're gonna do is set up our admin area alright and even if we go to actually let's just set it up first so to set up our admin user we need to do Python managed PI and then create super user okay so username just gonna use we'll just use admin and then email address it's not my real email address but whatever password I'll just do one two three four five six okay it's just telling me my password sucks but I'm gonna say yes we'll just bypass it I don't care ok so we should have an admin user so let's run our server with Python manage dot pi run server which is going to run it on eight thousand so we'll go ahead and open that up so we still have our landing page but we should be able to go to slash admin and see this log in and go ahead and use the super user okay so right out of the box we have this this functionality here where we can create groups we can manage our users we don't have to add any code for that we can change our password so pretty pretty damn cool now I want to add the functionality where we can go ahead and actually add questions from the backend here from the admin area so let's go back into vs code and let's go to polls admin dot pi because this is where we want to want to be able to add admin functionality so first thing we'll do is bring in our models so we'll say from and we can just say dot models we're going to imports question choice okay so we're bringing in those models and we should just be able to register them so we can say admin which is brought in up here from this Django dot contribs oh a demon dot site dot register and just put in question and admin dot site dot register choice and let's save that and let's see what happens here so if I reload you can see we got polls so it's up basically our polls app if we look at questions we have what is your favorite Python framework so basically I mean we put this in the database through the shell but of course we can see it in the admin area because it's all go looking at the same place now if I click on it we're just gonna see the question text right there's there's no correlation here with the choices if I go back here two choices we just we just see the choices and if I click on one we can see the question so we can basically choose the question from the choice but that's not really how I want to do this or how we should do this I want to have questions where we can go and we can see the choices here so there's a couple things we need to do we're gonna go back to to our admin page here admin file and I'm just gonna comment these out and I'm gonna have two classes here now we want to have those choices within the questions admin screen and we're going to use something called tabular inline to be able to do that so we're gonna have a class here and we're gonna call it choice in line and it's gonna extend from admin tabular in line like that okay and then here we just need to specify the model which is going to be the choice model okay and then we can also specify extra so basically how many extra fields do we want and I'm gonna use I'm gonna say 3 ok so that's pretty easy then we just want another class called question so the name of the model and then admin and we need to extend admin dot model admin ok and in here we're gonna set the field sets so field sets is going to be an array and in here we're going to open up some parentheses the first is gonna be a name which we don't need a name here so I'm gonna say none and then we need an object or a dictionary in Python with fields and we're going to set that to some brackets with the question text all right and then after this parenthesis right here we also want the date so I'm going to put in another set of parenthesis and let's say date information as the name here and then same thing fields fields and let's do pop the publish date or pop date and then we're also going to set we can set a classes option so classes and this is just how it's going to behave we're gonna do collapse okay and then we just put right here another comma wait is it here yeah another comma the reason we have this is hanging comma here is because this is actually a tuple this is the first element in the tuple this is a second and we need to have a hanging comma it's just a Python thing alright and then we're just simply going to set in lines to the choice in line class that we created above all right now as far as the registration goes we're just gonna say admin dot site dot register and instead of registering sorry if you can hear my daughter and her crazy friend upstairs yelling instead of registering just question we are gonna do question but also we want the question admin class alright so that should do it I'm gonna save it I have the prettier extension installed in vs code that's why it just kind of cleaned up a little bit when I saved so let's check this out if we go back to our admin and we reload we should no longer see choices because we don't have that register admin site registered choices we have questions and if I click on it and then I click on a question that's what we should see okay so pretty cool not not a lot of code you know this is not a lot of code at all and we get this really cool functionality okay and we can change the votes if we want we can manipulate the system se3 Django save okay and that should save it if we go back and there we go just like a good Russian we hack the votes alright so let's go back to vs code and the last thing I want to do in this file is just change the the site header and the site title because right now it says Django Administration I mean you're not going to want that there especially if you're you know building a site for a client so we can easily do that change that with admin dot and this is all in the documentation there's a lot you can do and a lot you can customize I want to set the site header to let's say pollster admin and let's do so we'll do admin site site title pollster admin area and then let's do index underscore title and we'll say let's just say welcome welcome to the pollster admin area so save that and if we go back and reload now you can see we get this pollster admin we also change the title alright good so now we're done with the admin file now we want to work on the front-facing website because right now all we have is the admin area and that standard landing page so let's go to our views let's go to polls views dot pi and by default it brings in render from Django shortcuts and this is used to render views or render templates and we're gonna have actually let's bring in our models first so let's say from da models because we're gonna have to query the database get the data and then pass it into the view so let's say from dot models imports question and choice and to create a view let's create our first view which is going to be let's say gets questions and display them so we define a function call it index and these are going to take in a request okay so I'm taking requests and then we want to you know what let's just return a template first so we can say return render and we hope we pass in our request and then the location of the template so we're gonna say pulls slash and then we'll have a file called index.html so just doing this should load the template now we have we haven't created the template yet we also haven't created the URL to that we want this to display at so inside the polls folder we're actually going to create a new file called URLs dot pi just like we have in the main project folder so in polls URLs dot pi let's first let's say from Django dot URLs we're gonna import path we need this to deal with URLs and then also let's import all of our views so from all imports views and we can actually add a namespace here so when we create links and stuff because you might have you know certain you might have like a details view in your polls app you might also have one in your I don't know your your shop app or something like that so we can simply say app name equals polls okay and then we're gonna have URL patterns which is gonna be a list or an array and then let's set a path here and I'm just gonna leave empty quotes because I want this to be just slash polls all right so we're gonna leave this empty and then let's connect it to the index view so views dot and remember we called that that function or that method index and then we'll give it a name of index as well okay so we're basically creating a route here now this isn't going to do anything we need to bring this into our main URLs dot pi which is right here alright so I'm going to open that up and we need to from Django URLs your path is being brought in but we also need to bring in something called include if we're going to include another set another URLs file so I'm gonna go right here above the admin and say path let's do path and anything that is poles slash we're gonna go ahead and include the poles dot URLs actually this needs to be in quotes okay make sure we put a comma here so now what should happen is as soon as we go to slash poles anything it'll then look at the poles URL file which is here and this being blank it's just gonna it just mean slash poles right if we did slash you know if we did result it would be pole slash result so we're just going to leave that blank and it should point to the index view which is right here which should render poles index.html all right now we're gonna get an error if we go to that so if we go to just slash poles it says template doesn't exist okay because it doesn't we haven't created this right here index.html now there's a few ways we can do this as far as templates go we can create a separate templates folder in each app but that starts to get messy if if you have multiple apps so I don't want to do that I actually want to create a templates folder right in here alongside of poles and Polster so basically in this top-level Polster so it's a templates and in here let's create a folder called polls so basic not a file lost it templates folder called polls and inside polls are gonna create a file called index dot HTML and let's just say polls and save that now this still isn't gonna work because by default it's gonna look at a templates folder inside the app folder inside polls so if we want a global templates folder like this then we actually have to go into the settings file which is in here so settings dot PI and go to right here templates and you can see this this ders right here this directories basically we want to define our templates path so we're gonna say OS which is operating system dot path dot join so we're gonna just use the join method and say from the base directory and then we want to go into a folder called templates ok and you can call it something else if you wanted to but I think templates make sense so doing that if I save and then I think we have to restart the server so let's restarted and now let's go back and reload this there we go so now it's looking in the correct location for our templates alright so we'll close settings now instead of creating you know a separate head body tags and you know we're gonna use bootstrap so we need to include the CDN I don't want to do that in every single HTML file we create so we're gonna have a layout or a base template so inside templates not in the pols folder but just write in templates I'm gonna create a file called base dot HTML and this base hTML is where our head body tags and all that stuff is gonna go so let's go ahead and put this in here and for the title will say pollster and then you might you might want different titles for different pages so we can actually use this syntax here this curly brace and percent and we can simply say block title and then another set of tags and say block or what is it end block okay I'm also going to include bootstraps so I'm just gonna head over to get bootstrap comm get started and just grab the CSS here I don't we don't need the JavaScript we're not doing anything with that so I'm just gonna grab that and put that right here okay and then in the body I'm gonna have a container class and then I want this to be a really skinny narrow layout so I'm actually gonna create a bootstrap row and then a six column div so call him d6 and I want it in the middle so M dash auto now here is where we want to output any content any any other templates that we want to display such as the index template so to display that we put in our tags and we just say block content and and block alright so we'll save that pretty err just kind of messes with it a little bit and then if we go back and reload oh wait a minute we didn't extend it so we created the base HTML but in the index.html we actually have to extend it if we want to use it which is good because then you can have we can have multiple base layouts if you want so from here let's let's put up at the top put in some tags and we're gonna say extends and this is similar to many other template languages we're going to extend base dot HTML and then put our content block so block content and end block and in here for now I'll just say polls again I don't like how prettier messes with that you know what I think I'm gonna just or it's not a prettier itself it's format unsaved so I think I'm just gonna shut that off I'm gonna go to my settings you might may or may not have this on but I have format on save I'm gonna uncheck because I don't like how it does that so if I put this back and save now it doesn't mess with it all right so let's go back here and reload and now you can see that bootstrap is enabled and we have the title so that's working out so let's see what do we want to do next we want to list the questions here right so we need to go back to the views dot pie because right now we're simply showing index.html we need to pass in the data in order to loop through and show the polls show the questions so in the views dot pie in index let's say latest underscore questions or question underscore list and let's set that to the question model thought objects remember when we did like objects dot all objects dot yet we did that within the shell well we have the same structure the same abstraction within this views file so we can do dot all but I'm actually going to do dot order by and you can look in the documentation for all the stuff you can do but I'm going to order by the so I wanted to sending so I'm gonna do - pub date and then we can specify how many we want let's do five so : five and then in order to pass it into the template we basically pass it in as an object or as a dictionary so I'm going to create a variable here and common convention is to use context and then we'll create a dictionary which is like a JavaScript object if you guys are you know I know a lot of you guys are JavaScript developers so let's say latest question list and set that to our variable latest question list and then simply pass in context all right so now we should be able to access the data within index.html so let's go into index.html and inside the content here let's put an h1 I'm gonna give it a class of text center and a class of MB - 3 and just say pull questions okay and then we want to check to see if there's any polls so let's we can use an if statement here so when you use my tags I'm gonna say if latest underscore question underscore list and we just want to end that or actually what we want an else so we can say else and then we want to end if so else means that there's no polls so we'll go ahead and put a paragraph and just say no polls available if there are polls then we want to loop through them so we're gonna open up some new tags here and we're gonna use a for loop so we'll say for question in latest question list we need to end that so here and for and for each question I'm gonna have a card class with MB - 3 just margin-bottom 3 and side here we're gonna have card body this is just standard bootstrap stuff and inside here let's do a paragraph with the class of lead and then we'll put in since we're just outputting a piece of data we use these double curly braces kind of like you would in like a JavaScript framework so let's say question dot and then whatever field we want in this case I want question text okay so let's just save that and see what happens I'm gonna reload this and there we go alright so actually you know what I wanted a navbar just to make it look a little better and - and to show you how to use partials but let's just finish this first so underneath the paragraph I just want to links 1 - vote to go to the vote page and one to show the results so I'm going to put an a tag here now I'm not going to use a regular link we're going to use the template syntax for a URL so we want to put some tags in here and we can say URL and in here remember we added the namespace to the to the polls right here this app named polls so we want to use this right here so we're gonna say polls and then we want the view that we want to load which is going to be detail okay which we haven't created yet and then we want this specific we need to pass in the specific ID so that it knows which question we're talking about so we pass in the question ID all right and then I'm just going to add a class here of BTN - s set let's do BTN BTN primary and SM and let's say vote now and then I'm just gonna copy this and right below it this one's gonna go to the results which we haven't created yet we need to pass in the ID I'm just gonna change this to secondary and make it a different color and change this to results so let's save that and see okay so it's giving us an error just because detail isn't found yeah so I mean I guess we can just comment these links out just for now it doesn't know what this is wait reverse for detail not found so even if it's commented out it's still gonna give us an error all right so we'll just leave that for now but I want to show you how we can add and now actually will do the nav bar after let's just finish this so let's go back into views so right now we just have our index let's do our detail so we're gonna add another view method here and this is gonna show specific question and choices okay so def detail let's pass in requests and we also want the question underscore ID as a parameter all right now I'm going to use a try block here we're going to say try and then assign a variable or assign question dots objects dot get remember we did this in the shell and we're gonna say the primary key is going to be equal to the question underscore ID which is actually going to come in from the URL it's gonna be a parameter so I'm gonna try that and then let's raise an exception so we'll say accept and then question dot does not exist okay so if it doesn't exist basically if we're looking for a question ID that doesn't exist then we're going to go ahead and raise in HTTP 404 status so HTTP 404 with a message of question does not exist okay and if everything goes okay then we'll return a render let's return a render and we have to pass in request and the template we want to load is going to be pull slash results dot HTML and then we're just gonna pass in the question as a dictionary okay which is this right here so that should load the details yeah so let's save that now we need to add a route for this for the detail so let's go let's go to polls and then URLs dot pi and right now we just have the index so I'm going to put a comma comma here and then let's say path and in here we're actually going to use these angle brackets and because we're passing in a parameter it's gonna be pole slash and then the ID so it's going to be an int and it's going to be called question underscore ID so that's where we're getting this right here this question ID right here is going to be passed in through the URL because we because of this alright and then let's save use dot and we called it detail and then we'll give it a name of detail all right so let's save that is this still not gonna work let's see okay so we didn't do the results yet I guess it's just it's not gonna work until we're done really well I guess we could take this out cuz it now we're getting an error because it doesn't know what to do with this so if I just delete that let's make sure that it works yeah okay good so vote now when it goes to pull slash one template doesn't exist because we didn't create it yet but at least we know that that works so let's put that back and now let's create this results method in the view and then create the URL for it alright so let's see results is actually gonna be pretty easy so this view method is going to get question and display results okay so we'll say def define results quest it's also gonna take the question ID as a parameter it needs to know which one and then let's say question equals and we're going to use a get underscore object underscore or 404 which is gonna look in the database for what we're asking for if not it's going to return a 404 okay so we're gonna say question and then the primary key is gonna be the question ID whatever is in the URL alright and then we're gonna return render request and the template is going to be pulls slash results dot HTML and we're going to again just pass in the question data so question all right so now if we go back and reload okay we didn't add the URL so let's go to our polls URLs PI and this time I'm actually just gonna put a comma here and copy this down so this is gonna be results it's gonna be views dot results which we just created and then it's gonna be the ID slash results like that actually let's put a trailing slash on this as well all right so if we save that now we shouldn't get this error good so now we have both of these buttons however we haven't created the templates yet we've created the views but we haven't created the templates so let's go ahead and do that so under templates polls we're gonna have two more HTML files we're gonna have results dot HTML and we're also gonna have what was the other one results detail so let's create detail dots HTML so we'll start with detail dot html' now I think I'm just gonna start to paste some stuff in just because this is getting really long so yeah let me just paste this in and I'll just go over it all right so we're extending base HTML just like we did in the other template we have our main block content up at the top I have a button that's going to go back to the polls okay back to that page basically back to this page right here so polls index all right then we have just an h1 that's going to have the actual question now if there's an error message we're going to display it here okay inside of an alert then we just have a form with an action that's gonna go to polls vote which we haven't created yet this is going to be our last view that we create within our polls app is vote and it gets passed in a question ID methodist post and then this is our CSRF token which is for across sites protection it's protects against forgery so basically you can't submit a form from you know it's just a security feature that's included with django and then here we're looping through all of our choices remember we use this right here question choice set dot all we use that within the shell so it's the same abstraction and then for each one we're going to display a checkbox all right so each one will have a value of the choice ID okay so it's going to get the ID of that choice the ID the HTML ID is going to be choice and then this for loop counter is just another feature it's just going to be whatever the that count is and then same for the label and then for the label we're gonna display the choice text so you know Django flask web to PI so for each choice it's going to display a checkbox and then we just have our submit so that's the entire detail so I'm going to save that now it's going to results so results again I'm just gonna paste this in so again works were extending base HTML we have our content we have our question text and then here we're looping through the choices ok we're using choice set all and then for each choice we're gonna show the choice text and then we're gonna have just a badge with the word or with the number of votes so choice dot votes and then vote now what this is is a helper so it's gonna look at this and if it's one then it's just gonna be nothing it's just going to stay it as the word vote if there's two or more then it's gonna PluralEyes it it's gonna be votes which is pretty cool it's a nice little helper and then down at the bottom we just have a link to go back to the polls or to vote again so let's go back here and wait a minute this is the results that doesn't make any sense and get all get object at 4:04 is not too fine we didn't bring that in but this should go to the vote to detail so I must have messed something up in the views oh yeah right here so in the detail I actually put results HTML to load and that's not correct we need is it what is it detail yeah detail HTML so let's try that vote not found vote is valid new function or pattern name okay so it's just it's telling us that because on the detail page this right here so if it can't find what this is then it's not gonna it's going to give us an error it's not even gonna render so we might as well just create our last view method which is vote so that's where the form submits to so I'm gonna I hate to do this but I'm gonna paste it in I hate copying and pasting but this is taking quite a bit of time so I'll just go through it where we're gonna have a function called vote question ID it has to know which one we're voting on this request dot postage request dot post choice is going to be if we look at the form is going to be this right here whatever this value is okay so it's gonna be the ID of the choice that's going to be submitted here and you can print that out if you want and then we're gonna try to get that question based on the ID and then we're gonna set a variable selected choice based on that choice okay if that choice are basically if it if they don't select a choice then we're going to render the details template and we're gonna pass in this error message if you remember in the detail template we have this right here it's checking for error message so it'll display here if they don't they actually don't make a choice okay so let's go back to views and then if everything goes okay then we're simply gonna add one to the votes okay the selected choice dot votes and then we're gonna save it to the database and then just simply return we're actually going to redirect to the the results now this reverse method and this get object or 404 we need to bring in as well as this HTTP response redirect all right so let's bring that stuff in up here so it's two from Django actually I'll just paste this stuff in okay so this is just the stuff we need to bring in now in order to submit the the voting form and call this method here we need to add a you a final URL to our polls URLs dot PI file so I'm going to copy this down and this is gonna be called vote and it's gonna be views dot vote which calls the vote method and then it's gonna be the ID slash vote so I'll save that let's go back there we go so if we say vote now what is your favorite Python framework let's choose flask and click vote and now we get go to our results so it redirects us to results and you can see one vote awesome so that seems to be working if we click results we see our results cool so that functionality is pretty much done we can you know we can manage our polls from the admin area of course and we can also vote on the front-facing website so the last thing we're gonna do is add a just a simple landing page and also a nav bar now with this templating we can have partials so I'm going to go into templates and I'm gonna create a new folder called partials and I'm just going to create a new file and I'm gonna call it underscore navbar dot HTML the underscore just just signifies that this is a partial and it's not a full template and I'm just gonna paste the sentence very very simple it's just a bootstrap now I've bar with no no links or anything at all so if we save that now we have this partial and let me just close all this stuff up so I know this is probably confusing but we're gonna bring that into our base HTML okay so our base HTML file let's go right above the container and let's put in a nav bar and we can do that by using template syntax and using include and then we want to go into partials slash underscore now bar dot HTML so let's go ahead and reload and there we go alright now last thing we want is our landing page because we've been working with the polls route this whole time if I go to just the localhost you know eight thousand there's nothing here so I'm gonna create a Pages app okay just like we have a polls app I'm going to close all these up I'm gonna just stop the server and do Python managed dot pi and this is this is only going to take a second so manage dot PI start app pages so now we have a pages folder and really all we need to do here is create a view and I'm simply going to render a landing page so let's do def index request and return render request and it's gonna be in pages slash index dot HTML and that's it there's no data or anything like that so close that we do have to create a URLs file in our pages folder so let's create a file called URLs dot PI I think they should just generate this with each app I don't know why they don't and then let's just copy from our polls URLs just grab this and paste that in and this is going to be much simpler we just need one route we don't even need this and path is gonna be up just views dot index index now remember we have to bring this into our main URLs file which is pollster URLs and yeah we're just gonna do a slash and that's gonna go to pages dot URLs okay so now we just need to create in templates let's close this stuff up in templates let's create a folder for pages and let's create a file called index.html and let's see this is gonna be very simple I'm going to just paste it in so we're extending our base adding our block content and we just have just some text and a link to the available polls which is the polls app and the index view all right so save that and let's run our server and let's go to our landing page alright so I know what I did I always do this inside our pages not pages inside our main URLs I where I linked where I included pages URLs this shouldn't be a slash it should just be empty so let's save that and reload and there we go so now we have our landing page so if I save you available polls there's our poll I can vote ok so that's all working good now let's add one more upsets the old one let's add from our admin area another question and just make sure that that works so we'll go to questions and add question say what is your favorite j/s framework react you singular and we'll say other okay we'll save that actually we need to put the date in the time we can just say today and now and save okay so that got added now let's view site and there it is favorite J s framework we'll go ahead and vote I'll save you and there we go so we get our results all right so I know that that was you know this was a long video lots of code but if you think about it for the functionality we have an admin area where we can do crud functionality we have you know authentication admin admin roles and stuff like that and then a front-end where we can vote we have you know relationship relationship in our database so it's a lot of functionality for a small amount of code but I mean this was a pretty long video so if you made it to the end congratulations hopefully you enjoyed it again I do have a series where we build an API with Django and use react on the front-end and I also have a you to me course called Python Django dev to deployment which you might want to check out as well alright guys thanks for watching and I'll see you next time
Info
Channel: Traversy Media
Views: 272,861
Rating: 4.9297895 out of 5
Keywords: django, python, python django, django 2
Id: e1IyzVyrLSU
Channel Id: undefined
Length: 71min 51sec (4311 seconds)
Published: Wed Sep 04 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.