Python Django Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey guys welcome to the Python Django crash course in the next hour or so I'm gonna cram as much info as I can about the Django framework we're gonna take a few minutes to talk about what it is look at some slides and then we're gonna jump in and we're gonna build a simple blog application with an admin area now this video is for absolute beginners people that have to have basically never used Django before and want to learn about it or have used it very briefly and don't really understand it and don't really understand the file structure and all that I will have more advanced videos on Django in the future but this is basically a starting point for people that want to learn it okay I know I have a lot of JavaScript developers subscribe to my channel because that's mostly what I do but I would encourage you to take a look at Django even if you don't know Python it's a very high level language I'm sorry high level framework and it does a lot of the heavy lifting for you alright so sit back relax and let's learn Django this video is sponsored by GPD host they offer a variety of affordable hosting plans with flexible billing cycles these plans include a free ssl certificate a free domain name website builder and many other services including free website migration with no downtime to find out more visit GPD host com or click the link in the description below alright guys so I do have a to do list django project video and i'm not really happy with it because i didn't do much explanation it was more of a code along type video so I wanted to to remake a basic Django course and explain things a little more go through some slides so we can talk about exactly what it is the type of design pattern it uses some of the advantages things like that alright I'm also doing this on Windows I did the other one on Linux Ubuntu the reason for Windows is because a lot of beginners use it and also setting up Python and Django on Windows is a bit different than doing it on a Mac or Linux it's gotten much much easier I know that you may have heard in the past that it's it's really difficult but it's it's very very easy now and you'll see that so this is completely cross-platform the the framework itself does not change depending on what system you're using so don't worry about it if you're on a Mac or Linux you'll be able to follow along just fine all right and as I said even if you don't know Python just follow along it's all convention if you if you understand basic programming fundamentals like functions and if statements and things like that you'll be absolutely fine so what exactly is Django it's a high-level Python web framework and I'll talk about high-level and low-level in a minute it's also free and open source like most great frameworks it really encourages rapid development and getting things up and running very quickly it follows the mtv or model template view design pattern which I'll talk about in a few minutes as well alright so like I said Python Django is high-level compared to a low-level flame framework like flask which is also a very popular Python framework now with flask you're free to do things on your own in your own way one flask application can look completely different from another in terms of the you know the folder structure and all that type of thing even if the functionality is very similar well with Django there's certain ways to do things the Django way it's very opinionated similar to Ruby on Rails if you've ever worked with that framework which is a great framework now you may even you may think that having more freedom is better and that may be true in some cases for some developers and some applications but for the most part Django is going to have you do things that in the best way possible the best and the easiest way possible and not let you screw yourself up so with that said Django is a great framework for beginners in my opinion so what are some of the advantages to using the Django framework as I said it was created for rapid development so it's great to get something up and running very quickly you can create an entire back-end administration system for your models and minutes and then every model you create it's very simple to add to that back-end Django is full-featured and fully loaded it has a ton of functionality in its core like user authentication administration RSS feed sitemaps we're not going to get into all that this is kind of just a basic overview but that stuff you know it is included and it is a pretty put together framework now for the size and the feature set of Jango it performs very well it's secure and it protects you from things like SQL injection cross-site scripting attacks and cross-site forgery things like that Django is also very scalable it can handle lots of traffic in the next slide we're gonna look at some of the sites that that do use Django or have use Django in the past it's also very versatile it can be used to build all kinds of diverse applications from social networks and content management systems to things like scientific computing platforms and of course it runs on Python which is a very powerful and versatile language itself so these are some of the sites some of the names that use Django or have used Django in their sites or part of their sites and applications now when any huge name uses a framework it's usually highly customized sometimes beyond recognition but all they all run Django at their core okay so they just modify it to their needs so sites like discuss Instagram Pinterest these are all a plus companies and web sites even NASA uses Django in their stack which shows you how secure it can be all right so it's extremely powerful even for you know services and in sites like this okay so let's talk about design patterns now I'm sure many of you have heard of MVC or model for your controller it's a very popular design pattern that separates parts of your app and puts the handling of you know incoming requests and routing things like that into the controller the data access into the model and the user interface component into the view well Django is sometimes referred to as an MVC framework and that's not completely wrong it is heavily influenced by MVC and it does use many MVC concepts however the sea or the controller is mostly handled by the framework itself and it works a little different so it's put into the mtv or model template view pattern okay which word works a little different basically it's you know just like MVC that it has a data access layer in the model anything to do with interacting relating data validating data that's all gonna go into the model the template is the presentation layer so all presentation related decisions go here you know how things should be displayed on the webpage or whatever type of document and then the view is basically the lot the basic logic layer okay it can access the model directly and displays the appropriate template so the view works kind of like a view controller and that's basically a bridge between the models and templates okay a lot of what a traditional controller would do an MVC is handle actually handled in the view okay so that's the biggest difference between how Django works and then traditional MVC like let's say Ruby on Rails all right another unique thing about Django is that it uses the concept of apps now usually you think of an entire project as an app but within django a single project or website can actually include multiple of what they call apps so you could have for example a blog app a client app to handle your client functions a store app and so on now of course you can have a single app in your website that you know if it's a blog or and that's basically what we'll be doing you can do that that's just fine you can also move apps from one project to another pretty easily and you can even use other people's apps pretty easily so this whole paradigm is very flexible and very scalable and reusable all right so the last thing before we get started I want to talk about is Python has something called virtual end for virtual environments which gives you a virtual environment for all of your PI Python instances and this is this is what's recommended to use with Django it's really easy to set up it gives you isolated environments with their own directories you know this is the recommended way to develop django apps it's not absolutely necessary but it is definitely recommended now this used to be very difficult to do on Windows but it's much more simple now in fact you know everything to do with Python as much is much more simple on Windows so if you are on Windows don't worry about it I'll show you exactly how to do it all right so that's gonna be it for the slides guys let's go ahead and jump in and let's set up Python we're going to install Python from scratch we're going to setup Django with pip which is the the package manager for Python we're gonna set up our virtual environment and then we're gonna build our simple blog application alright so let's get into it alright so the very first thing that we're gonna do is install Python now at this time the latest version is for Python 3 is version 3 point 6 point 3 and it's depending on when you're watching this it may be a later version but you should be alright alright so we're gonna go to python or i'm gonna go ahead and download it and save it and just open it when done and it's just gonna be a simple windows installer and like I said you know installing Python on Mac or Linux is gonna be a little different so just you know it's all over the web just those tutorials there's all kinds of stuff if you want to watch my to do app video that'll show you how to get everything set up on a bun too although I think we use Python 2.7 in that video if I remember correctly but let's go ahead and click run and we're gonna install let's see I'm going to make sure that you click Add Python 3.6 to your path so that you can run the Python command let's see we're gonna say customize installation I just want to make sure that we have everything we need now pip which I said is the package manager for python it's kind of like NPM for nodejs in JavaScript or it's kind of like gem ruby gems for Ruby on Rails you definitely want this included now this is something that that has been made much easier because before you had to install it separately when you're using Windows so now it's included with this Installer which makes things much easier so let's go ahead and click Next and it's going to install it in this directory here that's fine let me just check this stuff yeah that should be good so we'll click install and it's gonna get python set up on our system alright so that should be set up let's go ahead and click close and now we should have Python installed now as I told you guys before I'm gonna be using MySQL so if you're on Windows what I would suggest doing is installing xampp or actually if you're on Windows or Mac or Linux it's actually a completely cross-platform but this includes MySQL Apache PHP it also includes a tool called PHP myadmin where you can you know manage your MySQL databases and look at your tables and all that now django uses database migrations so we can actually do everything through our application rather than going into mysql itself but PHP myadmin is really good to actually see the stuff that happened that the migrations did the tables that created and all that so we will be using it for that so if you want to follow along you know exactly then go ahead and get xampp installed alright so let's close that up and let's open up a command line so I'm going to open up my standard Windows command line as administrator now if you're on Mac or Linux just open up your terminal and usually if you guys have watched my videos in the past I usually use git bash on Windows instead of the standard command line but I've had some issues with Python and Django and the virtual environment using git bash so we're gonna use this so what I'm gonna do is first of all just make sure that Python is installed correctly so it's a Python version alright we'll also check on pip which is the Python package manager good and we need to install the virtual environment okay so we need to install something called virtual environment wrapper now for that we use pip so we'll say pip install virtual env wrapper okay now if you're on Mac or Linux you can do that but if you're on Windows you just want to do - win okay now it says it's already satisfied because I already have it installed yours may look a little different but it should say it's installed successfully all right now once you do that you can create virtual environments now before I do that I'm going to just go into where I want to create my project so I'm gonna CD dot dot into my C Drive and then I'm gonna go to users slash Brad slash projects oops slash projects and it's clear this and then from here we're going to make a virtual environment we can do that with MK virtual env and then name it I'm going to call it PI one alright and what it's going to do is it's going to create a directory in your users folder called env s so you can see right here Ian vs / PI one this isn't where we actually create our project or anything this is just where the environment files go all right and now you can see right here we're using PI 1 now if you have multiple environments and you want to switch you just do work on and then the name of the environment so work on PI 1 alright so now we're ready to actually install Jango so let's say pip install Jango alright and that's going to basically install it globally and it might take a minute all right so now Django is installed I'm just gonna clear this out and we're going to basically generate an application and we can do that with a utility called Django - admin ok and we're gonna run a command called start project and then we're gonna name the project I'm just gonna call it Django project ok so now if I were to do a dir or LS or whatever and just to see what we have here you'll see there's a folder called Django project so I'm going to CD into Django project alright and then we want to open up our text editor here so I'm using Visual Studio code so I'm able to just do code dot and that'll open it up in that folder alright so let's see what that actually gave us creating our Django app so we have another folder called Django project which has a couple files and in addition to that folder we have a managed PI file alright right here I'm getting a warning or info saying the python extension is recommended if you're using vs code so I would also recommend that so if you want to go to extensions right here and search for Python it's this first one right here we'll just click install and that just gives us like some you know intellisense and hinting and stuff like that and then we can just hit reload and now we have the python extension installed alright so anyway the the managed PI is the the CLI client or the this the command-line interface tool that we use to do different things and it's basically a wrapper of Django admin ok remember we use that Django admin to create our application manage dot PI basically is the same thing except it's localized to this specific project so we use it to do things like run migrations run the cert the dev server things like that ok and the actual file the code here we don't need to do anything with it's just the utility that we're going to use within the command line all right now in Django project we have a couple files this double underscore init double underscore PI now this is complaining about pile inter not installed I guess no I don't want that let's say disabled all right so this file is empty by default and we're going to keep it empty this is required just to be here to treat the directory as containing packages by default it's empty and that's fine like I said we're gonna keep it empty but just having it here gets rid of some confusion that has to do with file names and modules and things like that all right so nothing that we need to deal with settings dot PI has all of our settings and I'm not going to go through everything here basically you can see that our base directory secret key this is your production key you don't want to share this if you push your code to github you don't want this included this this is for things like encrypting sessions things like that all right we also have the debug value set to true which is what we want for now in development that's going to give us you know helpful messages things like that before you deploy you're going to want to set that to false you're also going to want to include your domain names that you want to use for this application when you deploy in this allowed host array down here installed apps any application or any app you create you need to add to this array here and you can see there's some core apps that are that are included including the admin app Django comes with an entire admin administration area which is an application itself or I should say app that's what they're called in Django and in Django but that's included authentication sessions all that stuff is already here ok middleware basically are these are components responsible for doing something for instance authentication we have our auth middleware that is actually dependent on the session middleware which is right here so the order of middleware is very important okay and you can also write your own custom middleware but that's way beyond this tutorial alright and then we have our templates options for templates that's pretty much it Oh database so right now we're set up to use SQLite 3 which is not a really great database for production applications like I said we're using we're gonna be using MySQL so we're gonna be changing this up quite a bit okay so that's the settings file URLs dot pi this is basically routing setting up our routes and URLs and they basically use regular expressions here for the URL patterns you can see there's already one set for the admin area so basically this means the this caret symbol here means start with so it's gonna look at routes that start with admin slash and then that's gonna go to the admin app itself okay it's each app will have its own URLs file and this is basically just saying anything that's admins slash is gonna go on to this URLs file and you'll see this later on it'll make more sense when we create our posts AB alright and then WSGI is the primary development platform for a Django it's it's basically the common standard for web servers web servers and applications when we ran that start project it set up a simple default WSGI configuration for us and that's basically what that is all right so that's you can see this the file structure by default is very very simple so what i want to do now is actually run our web server so let's go back to our command line here and let's run python and then we're going to use our manage pi okay which is our command line tool and then we're going to use run server ok that's the command we want to use and then what that's going to do is it's going to run the server on port on our localhost on port 8000 so we can actually now go to our browser and we can go to localhost ports or : 8000 and there we go so it says it worked you can congratulations on your first Django powered webpage alright so now our server is running now notice this message we get you have 13 unapplied migrations so if you're not familiar with migrations basically they're files that will do things to our database so they'll create tables they'll add data things like that and if you're familiar with Ruby on Rails or laravel or a bunch of other frameworks that use migrations they work in you know very similar so unapplied migrations means that there's basically migrations waiting and those are those have to do with the admin app that's that's included by default authentication users things like that they haven't been applied which means they have they we haven't created them in our database yet now we could apply them by running this command here Python managed PI managed up PI migrated but if we did that now it would go into the SQLite database which is not what I want to use I want to use MySQL so we're not gonna run that just yet we're going to hook up MySQL alright now in order to do that we need to install the MySQL client for django hartford python so let's go let's do control c to get out of this and we're gonna install it with pip so we'll say pip install and it's called MySQL client ok so now that we have that installed excuse me I'm losing my voice now that we have that installed let's go ahead and go to our Django project settings file and go to where our database thing is right here our database object our dictionary and I'm actually gonna comment this one out and then create a new one alright so we'll say databases equals some curly braces and we want to say default okay so default and this is gonna be engine alright so engine is gonna be Django dot DB dot backends dot MySQL okay just like up here they had SQLite three we're gonna use MySQL alright then we're gonna say put a comma there and we're gonna say name so name is gonna that's actually the database name now we haven't created it yet so what I'm gonna do is go to localhost / PHP myadmin which is a tool included with xampp to you know create databases and stuff now you can use your standard SQL shell if you want but this is an easier way so let's click on databases and let's create one we'll call it Django project and create okay so now we have that database created now we're not gonna have to go through and create our tables and all that that stuff is all done through migrations which is nice we just needed to create the database itself so for the name it's gonna be Django project alright then you're gonna want to put your database user which for me is gonna be route and you're gonna want to put your password which for me is one through six and then your host ok host is going to be localhost 99.9% of the time and you can also define port but we're gonna leave that blank all right so that's our database so let's save it and now everything should be set up so that we can run our migration and all those default those thirteen default migrations should now go into this database if we're lucky if things worked out right so let's go back to our command line clear this out and let's run Python managed PI and we want to do migrate all right so everything looks ok here let's go over to PHP myadmin and reload the database and you can see all of this stuff was added alright so we have our off user table this is going to contain our users we can have different groups ok different user groups all our migrations all our session stuff it all gets put in in the database and it's all we have tables for all that stuff so you can see how how easy it is to get this stuff set up ok now if we start our server back up so let's say python managed dot pi run server and you can see that that message about the 13 migrations is now gone and we reload it's going to work and we should now be able to go to slash admin and we have a back-end interface ok an admin interface now right now there's no user for us to log in as so we can actually use manage pi to create a super user so that we can log in here so let's stop the server with ctrl C clear and we're gonna do Python managed dot PI and then we want to run create super user I spell that right create super user space and then - - username equals and then whatever you want the name to be I'm going to use Brad and you also want to put your email so - - email and I'm gonna set that to Brad at gmail.com alright so we're gonna go ahead and run that and then it's gonna ask us for a password okay so I'm gonna do I think it has to be 8 characters so I'm gonna do 1 through 8 again oh it's too common ok so there's some rules it can't be all numeric so let's see I'll do ABC one two three double exclamation ok so now we have a password so let's go back to our well first we have to run the server again so let's do run server let's reload the admin page and now we'll log in with Brad ABC one two three double exclamation login and there we go so we have an entire back-end admin area and we can add groups ok we can add user groups here we can add more users if we want okay so username password password confirmation if we look at the users you'll see the Brad user we have which has staff status so there's a lot of functionality in a very very small amount of code I mean we really haven't even written any code all we did was change up some configurations and we already have all of this functionality alright so you can see that Django has is definitely for rapid development all right so right now we don't have any apps ok remember the concept of apps and we want this to be a blog so we need to create a blog gap or a post app is actually what I'm going to call it so I'm gonna stop the server here actually it's logout of the admin and let's ctrl C and stop the server clear this up and we're going to create a post app okay so we can do that using manage pies so we're gonna say Python manage dot pie and we're gonna say start app and we're gonna call this posts okay now if we look over in our folder structure we now have a post folder close that up we have a post folder and it has a bunch of files it has the init dot pi which we're just gonna leave that's gonna be blank it has an admin dot PI which has to do with adding models to your interface here so for instance we're gonna want to be able to add posts from the admin area we're gonna get into that later apps dot PI we're not really gonna mess with it's basically app specific settings models is where we create our models so we will have a post model tests for testing which we're not going to get into and then views is basically it's it's basically our controller this is where we create like our index our details method which is going to we can interact with the model we can pull our pose in and then we can load templates or load views from here as well so you'll see all how all of that works all right now before we can actually use our post app that we just created we have to go to our Django project settings dot PI and add it as an app all right so up here we have installed apps I'm gonna put it right as the first one and we're just gonna put in posts okay and put a comma here okay that has to be done now what we want to do is go to the URLs pi that's in the Django project and we basically want to say we want to put another one of these just like admin goes to the admin app we want anything that goes from posts to go to our application now to include our application we can use the include method and we can say posts dot URLs okay now this include method or function right here this is this isn't gonna work by default we're gonna get an error because we need to import this okay just like we imported URL to use that we need to import include so we're gonna put a comma here and say include alright and we can actually get rid of all these comments here we don't need this alright so basically what's going on is anything that goes to slash posts in our application so slash pose slash is gonna then get passed on to the URLs file inside of our post app which is not there yet you can see there isn't a URLs file we actually have to create that ourselves alright so hopefully that makes sense so let's save this alright and let's go to our post app or post folder that we have here and create a new file called URLs dot pi okay now just like the other URLs file we need to import a couple things so we're gonna say from Django dot conf URLs we want to import URL and include ok actually I don't think we need include here just URL and then we're also going to want to import our views okay so we're gonna say from dot meaning from all we want to import views okay now we want to create a URL patterns array oops so URL patterns and you can see if we look at the other URLs file we're doing the same thing okay so in here what I want to do is I want to load a an index method in the views file so we're gonna say URL I'm sure you don't you might see me use semicolons in Python we don't use semicolons but I'm at my core I'm a JavaScript developer and a PHP developer so you may see me mess up and put a semicolon in here and there all right so we're gonna say R so basically route and we want a route for just slash posts okay not post slash you know something just posts so the expression here is gonna be caret which is gonna it means start with and then money sign which is end with okay so basically start with and end with nothing so post slash nothing that's what this what this means and I know that may be a little confusing all right and then what we want to do is put in a second parameter here and we're gonna save views dot index so it's gonna look in our views dot Pi file right here for a method called index okay and it's gonna load that and then we also just want to give this a name so we're gonna say name equals index like that alright so that's our first URL pattern or our first route so let's save that and then we're gonna go into our views dot Pi file and from here we want to create that index view our in index method so in Python to create a function or a method you use the DEF keyword so define index whoops define index now this is going to take in a request okay all our routes will take in a request and then we'll put a colon here so that defines a function and then in here what we'll do is we're gonna say return I just want to basically returned a response okay now ultimately we're gonna want to render a template but just to test things out I just want to send the response to the browser so we want to bring in something here from Django dot HTTP we want to import HTTP response okay and this is what we what we use to create a restful api so I'm going to say return HTTP response and then in here I'm just gonna put some text I'm gonna say hello from posts all right just like that so let's save this and now hopefully what will happen is we can go to slash posts and we'll see this in the browser okay so we'll probably have to restart the server you know let's go ahead and run our server so we want to do or is it managed up Python managed up I run server okay so now the server's running so let's go to slash posts and there we go hello from posts okay so we're not loading any views or anything like that all we're doing is sending out a response with some text all right just to show you how the URLs work how you know how these all connect together so just to reiterate I know that this this may be a little repetitive if you guys already understand but the main URLs file is saying anything that has post starts with post slash is going to be basically passed off to the URLs file in the post app which is this file okay and then we're saying for the route that is nothing so post slash nothing is going to load the index method from the views file okay we're also naming this index and then if we look in the views file we now have our index method okay and then we're just basically sending out a response with some text okay that's exactly what's happening now obviously we're gonna want to render a template so what we're gonna do is let's just comment this out because we're not doing that anymore what we're gonna do instead of returning HTTP response is we're gonna return render okay that's what's used to render templates and that's already being brought in up here by default so we'll say render and then we want to pass in our request and then we want to specify the template that we want to load okay so I'm gonna say posts slash index dot HTML and I know we haven't created that yet don't worry about it okay so let's save that now if we try to load this we're gonna get an error that says template does not exist so what we're gonna do is inside of our posts folder we're gonna create a folder called templates and then inside here we're going to create a folder called posts now I know this looks a little weird because it's posts templates posts but if we just put our templates inside our HTML files inside the templates it's going to get confused with other apps in their templates so you want to specify the name of the app here as well so let's create a file called index.html okay and then all I'm gonna do here is put in an h1 and say hello from index dot HTML and we'll save that and then let's go and reload let's see that didn't work posts index.html so we're loading that here let's see what am I missing might have to restart the server what do we got here turtle server power pose you know what let's uh let's restart this and run the server again and reload there we go so we just had to restart the server and you can see that it's loading the index.html file it's also parsing the HTML we have an h1 alright good now we're gonna want to have you know our head and body tags and all that in our HTML and we're not gonna want to include that in every single file so we're gonna have to create a layout alright so what we're gonna do is in our templates post folder let's create a new file called layout dot HTML alright and in here we're gonna put our basic you know HTML tags I'm just using Emmet so I did exclamation tab and it gives us this basic structure so for the title I'm just gonna say Django actually we'll call it traverse e-media blog okay so we'll give it a title and I also want to include materialise CSS which is a CSS framework so if we go to get started all we need to do is include the CSS link right here and then the JavaScript link so we're gonna paste this in the head right here and let's see actually we don't even need the JavaScript link because we're not doing anything to do with their JavaScript so just the CSS link now we're gonna want to do let's close that up now what we're gonna want to do is go to the body and let's put in a header ok so this is gonna be a very very simple layout my point of the point of this is not to create like an awesome-looking app it's just to get you to understand Django but then again I don't want it to look absolutely horrendous so we're gonna give this a class of container and the class of center - line all right and then here we'll put an h1 and we'll say I will say traversée media blog I guess doesn't really matter you guys can put whatever you want alright and then let's see so that I want to show on every template now obviously each template you create is going to be different you're gonna want different content so for that we need to put in first of all a container we're gonna wrap it a wrap everything in a container to move it into the middle and then we want to put some syntax here this is actually Jinja by default we're using Jinja templating which is a template engine like you know blade or underscore or any of those types of template engines and we're gonna say block content all right and then we just want to go right under it and we're gonna put in this is just the syntax the percent signs so here we're gonna say end block yeah and block alright so any other views we create or any other templates such as index.html this is where it's going to output but all this stuff is gonna be on every page alright so let's go ahead and save that let's go back to index.html and then we want to make sure we extend that layout okay I'm actually going to keep that h1 there but let's go up top here and let's say extends and then we want to extend from posts okay so we have it in the post folder slash layout dot HTML and then whatever we want to output in this block content we have to wrap that in block content so right here whoops so we want to put our percent our curly brace in percent and we're gonna say block content and then go underneath and say n block all right so now let's save that and reload and now we have our disgusting-looking header and our h1 all right I actually want to change this to [Music] an h3 and let's say I don't know we'll just say posts for now or let's say latest posts we'll also give this a let's give this h3 a couple classes that have to do with materialized so let's Center it so we'll say Center align and we can also change the color of the background so we'll say red and then I'm gonna say lighten - 3 so that'll give us like a light red so we'll save that reload and there we go alright so that looks a little better now we can pass dynamic data into our views okay or into our template so if we go to views dot PI right and we go and add another parameter here after the the template name we can put in a dictionary or an object and we can specify like let's say title actually should be title and we'll say latest oops latest posts alright so we'll do that and then we'll go back into index.html we'll replace this hard-coded latest posts with double curly braces and title and let's save and reload and you can see we still get latest posts and if I were to just just to make sure that it's coming from here we'll say latest post one and reload and we get latest post one okay so this is how we insert like our blog posts what we'll do is we'll create a model we'll get the data from the model and then we'll pass it into the view like this okay all right so let's actually do that let's create our PO model so just to clean things up I'm gonna close all this stuff and we're gonna open up inside our our post folder we can close the Django project inside post so we're gonna go to models dot pie alright so in models dot pie we're not gonna do too much here it's gonna be pretty easy we're gonna create a class called posts okay and inside here we want to pass in see how we're bringing in models right here we want to pass in models dot model okay we're going to put a colon and then go down here and put in the fields that we want so we want a title so we're gonna set that to models dot and then there's different types of fields we want a character field so it's actually char field okay and then we can put in here a max length if we want so let's say max underscore max length and we'll set that equal to 200 okay and then let's set a body so we'll set that to models dot and let's make this a text field which is a is more characters than a character field okay and then let's also do a created at okay we're gonna set that to models models dot date/time field and I want to set a default for that so we can say default equals now I want to use the date/time module we have to import that if we want to use it so we're gonna say from date/time import date time and then here in the default you know what let me just make this bigger so default equals date time which has a method called now alright so we're gonna say our property called now so date time now and we're gonna set blank equal to true okay so let's actually yeah let's let's save that so you can see not too much code there and then we'll switch over to our command line stop the server and then what we need to do is create a migration based off of this model because we're gonna want to create a table in our database that's going to hold post so it's going to hold a title body and created at fields so to do that we need to use Python Python managed dot pi and we want to run the command called make migrations so make migrations and then the model name which is posts ok so let's run that so what that did is it created a migrations file you can see right here it's the 0 0 0 1 initial dot PI all right now that just created the file if we go over here you can see it right here and if we look at it it'll show you the different all the different fields that it's going to create and stuff now it didn't create the database table yet just the file so to actually run it and create the database table I'm sorry table we need to say Python managed dot PI my grades okay so it looks like it went okay but let's go and check so we'll go to PHP myadmin reload and we should have right here posts underscore posts if we look at that we look at the structure we see ID which is our auto increment primarykey title body and created that so the fields that we added to our model in this okay so you can see how migrations are really nice because we don't have to go into the database ourselves and create these fields like we would with some other you know a lot of different PHP frameworks not laravel laravel is awesome with migrations but something like codeigniter or something like that we would have to create the fields ourselves all right now if we go to our admin area in fact I'm gonna add an admin link on the layout HTML file so let's go here and right under the end block we'll put a line break and then we'll put an a tag and we'll say admin login ok that's gonna go to let's uh let's make that go to slash admin and then I'm just gonna add a class here of center-aligned and let's check that out oops all we need to run our server that's right see run server where is it ok so you have admin login now it's actually not in the center because it's displayed in line so I'm gonna just take the short short route here and just put a style and what display is block like I said it's not about it's just about teaching you guys Django I don't care about style or anything like that all right so we have our admin login link so let's click that let's login with our user we created so let's see it was what was it ABC one two three exclamation all right so we logged in now this doesn't look any different okay we're not seeing our posts we can't create posts yet so the way that we can fix that is by going to our posts folder and going to admin dot pi and see how it says register your models here this is where we need to do this so first off we need to bring in our models so we're gonna say from dot models import posts okay and then all we need to do is say admin dot site dot register and in here put in posts let's save that let's go back to our admin and reload now you can see that we have our posts here now we can actually add posts from the admin panel now which is great but this right here is post with two S's at the end that's because we use plural a plural name for a model and it automatically is adding on an S here so this is actually a really easy fix all we have to do is go to our models file and we're gonna go right here and we're gonna say class meta and from here we can add different meta values so we want it we want to say verbose underscore name underscore plural and we can define what we want a plural name for this model to be which I want to be posts okay one s so if we save that and we go back and reload now it's just 1s alright so if we click on this now you see zero posts let's go ahead and click add posts and we now should have complete crud functionality for our posts let's say post one this is our first post you can choose a date and a time and save and there it is okay now notice how it says post object that's not very helpful I'll show you how to change that in a minute so if we say post - this is post to save again post object so to fix this we want to go back to our models and we want to go right here and we're gonna say define double underscore STR double underscore we want to pass in self and then this is where we can define what we want to show in that area okay we want the title so we can just say return self dot title and save and then we'll go back and reload and now we get post one in post two and just to make sure that we can update these let's say this is post two updated and save ok so successfully changed so all this stuff is taken care of for you that the flash message is everything just imagine doing this with you know nodejs and express and I love Express it's it's my favorite framework but I'm just saying Django has some real perks to it when it comes to rapid development so yeah so that updated good now the last thing I want to do is we're almost up I wanted this to be about an hour I want to save you site we want to show the blog post but let's take care of this first so right now if we go to our root it's page not found okay we have to actually I have to go to slash posts to see our blog now what you could do is create a whole new app for your site like our pages or something like that and have a home page but what I want to do is just make the root of the site go to the post page or to the blog so I'm gonna go to the main URLs file which is in Django project URLs dot pie and we're gonna go to the top here it's a URL and actually I'm just gonna copy this right here understand instead of posts we're gonna do start and then end ok so basically that this is the root URL and we want that to go to the post URLs so let's save that and now if we go just to our root URL and reload it's going to lo blog page all right so now let's take care of showing our pose here so we're gonna go to our view dot PI file it's in the post folder okay and we're gonna want to go let's see let's go right here and we're gonna want to basically just bring in the posts from the model okay so to do that we're gonna just create a variable called posts and we're gonna set it equal to capital P posts so the post model which we actually have to bring in so up here I'm going to say from models imports posts alright and then we're gonna say post on objects dot all ok we want to get all posts and then we can specify a number of posts that we want and I'm gonna specify : 10 okay so we'll get the first ten posts I'm not gonna get into pagination and stuff like that this is just a you know this is a crash course for the basics now we need to take this post object and pass it in to our template okay and we could just add it here but what a better cleaner way to do is to create a variable you could call it like data but oftentimes you'll see it called context and then we'll set that to an object and we'll take our title put that there and then we'll say posts and we'll set it to that post variable and then we'll simply pass in here instead of the the object or the the dictionary itself will pass in context all right so let's save that now our view should now be getting these posts that come from the model so what we have to do is go into our index page ok our index.html which is the viewer loading and we need to loop through the posts okay so I'm gonna put a ul right here with the class of collection which is a materialized CSS class and then in Jinja to do a loop we're just going to put our standard curly brace % syntax and we can say for post in posts all right and then when we want to end it we just say end for and inside here what we'll do inside here will have an Li with the class of collection item which again is part of materialized and then we can put our double curly braces and say post dot title all right so let's save that and let's go back to our application and reload and there we go post one and post two now we're gonna want these to link to details pages so I'm gonna wrap this in an a tag okay we want this to be wrapped around the title and the link here is gonna go to slash posts slash details slash and then the ID which we can get by saying post ID like that okay so if we save that preload okay now if I click that it's gonna say page not found because we haven't created this URL pattern and we haven't created this route but you can see it's going to the ID of one this one has the idea of two and so on so let's go ahead and go back into our URLs file of for the posts so it's a post URL spy and we're gonna see I guess I guess we could just copy this and this time instead of you know starting and ending with nothing we want this to start with details slash now we don't want to just go to post slash details because we need to get the ID from the URL so what I'm gonna do here is I'm gonna open up a set of parentheses and we're gonna put a question mark P which represents the parameter and it's going to be whoops it's going to be the ID parameter and we want this to be a number so we're going to use an expression here we're gonna use /d which means that it should be a digit and then the plus sign which means that it should be at one at least one or more digits okay and then we're just going to say slash money sign money sign representing the end okay now this is going to go I'm sorry this should go outside of the parentheses so it should be yeah slash money sign like that all right and then the the view is gonna be called details so views dot details and then for name I guess we'll say details all right so let's save that let's go to our views file and under the index we're gonna create def details okay so that'll take requests and also in addition to requests it's also going to take in that ID parameter alright so we'll be able to access the ID so we want to fetch a single post now so we'll create a variable called post from the post model we're gonna say objects instead of all we're gonna say dot get okay and we want to say we want to get where the ID is equal to the ID that's passed in here that's coming from the URL okay and then for the context I'm going to set the context and we'll set post to the variable post and then we simply want to load our template just like we did here I'll just copy this instead of index we want to load details okay which we haven't created yet so let's save that let's go to our templates post and create a new file called details dot HTML all right and then let's see in here we're gonna have to extend everything so I'm just gonna copy from the index.html and then just clear out actually we'll leave this we'll just change this to post dot title now the reason I'm using post dot title is because we're passing in post which is this right here okay and we're at we want to access whoops not that right there it's coming from here which is coming from the database and we want to grab the title alright so we want the title and then let's see we're not gonna want a ul here so we can get rid of that what I'm gonna do is put in a card class and we'll say card content this is all just materialized and then we'll put in the body we can access that with post body all right and then under the content we're gonna say card - action which is just another pot of materialized part of the card component and we're gonna put in post dot created at which is the date okay and then we'll just put a button down at the bottom to go back alright so this will go to slash posts I'll say go back and let's give it a class of BTN which is a materialized class alright so let's go ahead and reload let's click post one there we go this is our first post we have our date we have our back button post two and there we go and we have our admin login so if we wanted to update a post say hello world and save if we go back to our front end will save you site and there it is hello world alright guys so I know that towards the end this got kind of rushed maybe it might might have seemed but I just wanted to cram as much as I could and just get something up and running for you again this is for beginners this is for people that are just getting into Django so there's there's a lot of other ways to do things and of course you can have you know people add pose from your front end you can create a front end authentication system there's there's so much more you can do but again this is just a very generalized crash course so thanks for watching if you guys liked it please leave a like please subscribe follow me on social media whatever you guys want to do is fine and thanks for watching hey guys I just want to mention our sponsor GPD host so if you're looking for affordable fast and quality cpanel hosting look no further they offer many types of packages that include a free domain name free ssl certificate a website builder and more all hosting plans are completely managed and easy to work with you also get automatic weekly backups so whether you have a website to transfer or you're building it from scratch GPD host is a high-quality solution to learn more visit GPD host com or click the link in the description below
Info
Channel: Traversy Media
Views: 731,806
Rating: 4.9180102 out of 5
Keywords: djaango, python, python django, django tutorial, django crash course, python tutorial, python windows, django windows
Id: D6esTdOLXh4
Channel Id: undefined
Length: 68min 10sec (4090 seconds)
Published: Tue Nov 07 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.