Python from Scratch - Creating a Dynamic Website

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Another great (but significantly longer) place to learn Python for dynamic websites is taught by Steve Huffman (founder/programmer of reddit) at Udacity: http://www.udacity.com/course/cs253

👍︎︎ 3 👤︎︎ u/IsaacLean 📅︎︎ Sep 16 2012 🗫︎ replies

I suggest you try out the Django official tutorial. It's simply great.

👍︎︎ 2 👤︎︎ u/n1c0_ds 📅︎︎ Sep 16 2012 🗫︎ replies

Okey so the admin template generation is good and dandy if you are making your own little blog.

But what about big solutions with your own designs?

👍︎︎ 2 👤︎︎ u/[deleted] 📅︎︎ Sep 17 2012 🗫︎ replies

Thanks for this.

I've been learning Python for a little bit now but always find it difficult to apply what I learn to a project. Hopefully this will help.

👍︎︎ 2 👤︎︎ u/[deleted] 📅︎︎ Sep 16 2012 🗫︎ replies

What is 'from scratch' about this? Should be Django from the start - Creating ... Would love to see a real from scratch frameworkless dynamic website construction video.

👍︎︎ 1 👤︎︎ u/cinger 📅︎︎ Sep 17 2012 🗫︎ replies

Great! Thanks for the link!

👍︎︎ 1 👤︎︎ u/hlc 📅︎︎ Sep 16 2012 🗫︎ replies
Captions
hi everybody I'm Jars Laval and welcome back to Python from scratch a video series for net Tut's where we're learning the Python programming language this is the fifth and final episode in the series and today we're going to use everything we've learned in the previous four lessons to create a simple dynamic website with Python in the previous lessons we've covered some essential skills but we haven't actually learned how to use them for web development that's what we're looking at today if you know some Python but have never used it for web development then this is the right tutorial for you but if you don't know any Python at all then I really recommend you go back and look at the rest of this series to bring you up to speed because everything we're doing today relies on those previous episodes so with that out the way let's get started something to think about first is what's actually needed to power a website the fundamental process behind a website is that you have a program that accepts a request for a URL then processes it and serves up a response in the form of a HTML page along with all the other resources a web page needs like images and style sheets in languages like PHP this is easy because it's a specifically designed web language so all of that is done for you and all you need to do is code the functionality specific to your site however in other more general-purpose languages like Python it's not that simple if you wanted to you could write a Python program that does all of this but that's a lot of work and it's already been done many times by a lot of people so why go to the trouble these programs that serve up web pages like this are called web frameworks and we're going to use one today for making our website so there's a lot of good web frameworks out there but probably the most popular Python one is Django this is what we're going to use today because of all the ones I've tried it's definitely not as feature-rich and also there are some Django tutorials here on net touch so if this beginner intro interests you you can move on straight away to some more advanced stuff and I will put a link to those tutorials in the text of this article however there's a really big selection you don't have to stick with Django so let's just take a quick look at some of the other options available to you there is this one called web pie it's a lot smaller than Django and has less features as a result it was actually made by one of the guys at reddit and it was used to power reddit for several years so it's clearly very capable it's not actually used anymore and it is less feature-rich than Django but if you're looking for something even simpler than web pie is a good way to go there's a framework called rock which is it's more advanced than web pie and it probably has a feature parity with Django or you know getting quite close at least so if you're looking for an alternative and you don't like Django then grok is a good option there's one called turbo gears in the past this didn't have a great reputation because a lot of the documentation was bad and it changed really frequently meaning that your the program's you wrote in it had to change as well and making it difficult to update but recently it's it's apparently got a lot better so it's it's definitely a viable option if you don't like Django now obviously there's even more frameworks than this but I'll be sure to put links and descriptions to all of them in the text of this article so now we've had a look at some of the options let's focus on Django because that's what we're going to use today so obviously the first thing we need to do is set up Django with Python for us to make websites with and you are probably going to want it in two places one you'll want on your local computer for developing and testing your websites and then you'll also want it on a web server for deploying those websites to the public and we're going to look at both of those scenarios today but we're going to begin by getting it installed on our local machine it's a pretty simple process but obviously you will need Python installed for this so if you don't have it installed then go back to the first tutorial and you can learn how to get it installed there we're going to install it from the terminal and don't worry if you don't understand these commands they're not Python it is useful however to have a basic knowledge of the terminal if you plan to run a website with Python just for maintenance and stuff so there are some tutorials on the subject here on net Tut's and I'll make sure to link to those as well another quick thing to remember is that Django doesn't work with Python 3 so you need to be using Python 2.7 or earlier to continue like we decided on in the first episode so if you're on a Mac or Linux then just open the terminal this won't work with the Windows command prompt so I recommend something like cygwin to run through these steps so I will open the terminal and first we need to download the source archive so we're going to use you get to download it and we need to find the link so we will go to the downloads page and then copy that link and I'll just paste it in and let's download that and if you just give it a few seconds you should have Django downloaded to your machine so this is just the source archive so we need to actually extract the files and we can do that with tar so I think the option is z XZ V F and then just type the beginning and you can use a tab to autocomplete the file name okay and hit enter and you should see a load of stuff appear on the screen as they'd extract all the files so we need to change into that directory so CD and if we type the name and hit tab then we can change into the directory and then finally you need to install it which is just one more command so you need to do - setup PI and install and hit enter and that should run through and install it on your computer you may need to run that command as a super user by putting sudo before that command if you get a permission denied error and then finally if you want to you can just clean up the install files by changing out of that directory with CD dot and then you can remove the file so we can do recursively remove the Django folder and that will remove everything we downloaded and then we can remove the Django archive and then that should all all be gone and you'll have to Jang on your system so now all we need to do is test if Django works for us type Python to enter the prompt and then we are going to use the import statement to import Gengo to Python just like we learnt in the third lesson so we can type from Django import get version and this gets the get version function for us from the Django module and that's work so it's all looking good and we can now just run the get version command and we've got django 3.1 so we should see 3.1 and there we go that's worked so if all the steps have worked up to this point you know have django installed on your system and you are ready to do some local development of your websites with python so we'll take a look at installing Python and Django on a remote web server later in the lesson but for now let's have a look at creating our first project with it and starting to build a site and I'm going to change my documents directory so now we can run a command to start our first django project and for today let's create a simple blog as a test exercise so we access the Django admin file and this was installed when we first installed Django so it's called Django admin dot PI and then we will pass in the start project parameter and it will start a project for us and then you need to give it a name so we'll just call it first blog you can call us whatever you like and that's created our first Django project for us which is just a folder containing some template Python files so now we can change into that folder and it should be called a first blog okay and if we list the files we can see that we have got three files there so let's take a look at what all of those do so this first file in its PI tells python that this folder is a package and we saw these in the third lesson it allows python to import all of these scripts in the folder as modules manage pi isn't actually part of your website it's a utility script that you run from the command line and it contains lots of functions for managing your site settings pi obviously contains all of your website settings a django doesn't use xml files for configuration or anything like that everything is Python so this file is just a load of variables that define settings for your site finally URLs pi is a file that map's URLs to specific pages so for example it could map your website comm slash about to an about Us page and whenever your user clicks on link or types within the address bar it gets managed by this and sent to the appropriate destination so these are the basic files we've got so far however none of these files on their own make a functional website and for that we need apps apps or where you actually write the code that makes your website work but before we take a look at them we need to understand a bit about Django's design principles so let's talk about that now first django is an MVC framework and that stands for model view controller django actually calls itself an mtv framework which stands for model template view it's a slightly different approach from MVC but fundamentally they're very similar anyway MVC is an architectural pattern that provides a way of structuring your projects it separates the code that's used to process data from the code that manages the user interface secondly Django subscribes to the dr why or don't repeat yourself philosophy which means that you should never be writing code that performs a certain task more than once for example in our blog if we wrote a feature that say picked a random article from the archive and then we implemented this feature on multiple pages we wouldn't code it again each time it was needed we would code it once and then implement it on each page this also applies to work other people have done for example Django includes an administration system for managing your website and also an authentication system if users need to register to use your site in the past when I've written websites using PHP for example I've made these systems from scratch in Django it's already been done so there's no need to repeat it you can just use what's provided okay so how does this relate that to the concept of apps well apps allow you to write your website in a DIY style each project like the one we have here can contain multiple apps and conversely each app can be part of multiple projects using the example from earlier this means that if we made another site in the future that also needed a random page feature we wouldn't have to write it all over again we could just import the app from this project because of this is important each app serves one distinct purpose if you write all the functionality of your site within one app and then need to use part of it later again you'd have to import it all for example if you are making an e-commerce website in the future you wouldn't want to import all of the blog features however if you make one app for this random page feature and then another app containing the blog publishing system you could pick and choose the bits you needed if you ever relied on them again this also means that within the site the code is well organized if you want to change a feature you don't have to search through one massive file looking for the function you need you can go to the relevant app and change it without worrying about interfering with anything else okay so that's pretty much all you need to know about apps and Django's design conventions so let's go ahead and make our first one and this is where the managed by script comes in we can use it to create our first app so in the terminal we are going to tie - manage pie and then we're going to pass the starter parameter and then we're going to go our app a name and I'm just going to call it blog because this is where we're going to create all of the publishing functionality and we now have an app called blog we should now have a folder here called blog and this is our first app what it's going to do is get blog posts from a database and display them in a page so we'll list the files and see that it's there so just type ls' and you can see we now have a directory called blog and that is our app okay let's change into the folder and list the files to see what it contains so I'll CD in blog and then list these files okay again we've got an init PI file to make it a package and three other files models tests and views we don't need to worry about tests for now but the other two are important models and views are the M and V parts of MVC so in models we define our data structures if you've ever worked with PHP before you might have used PHP myadmin to create some MySQL tables and then written out your SQL queries manually in your PHP scripts in Django this is all much easier because it's abstracted for you by these models we define all the data structures we need in this models file and then run a command and all the necessary databases are made for us when you want to access that data you go via these models by calling methods on them instead of running Raw queries now this is very helpful because Django can use several data programs we're going to use MySQL for today because it's the most powerful and it's what most web hosts provide but if later you wanted to change then all of the code you wrote would still be valid because it's been abstracted by these models you wouldn't have any code that's specific to a certain database program in other languages if you wanted to switch to sequel Lite or something you would have to rewrite the code that accesses your database so what models will we need here well for a blog we'll need a table of posts and this will have several fields with one for the title one for the body text the author the time it was written and so on so a real blog would obviously have comments but that's beyond the scope of this lesson also if we weren't using a framework we'd need to create a table of users and then a system to make some of them administrators who can post blogs however Django does all of that for us as we just discussed and obviously we're following the DIY principle so today we're just going to make the one table and that is going to be for our blog posts we will get back to that later after we've discussed the views file so in the views file we write the code that actually generates the webpages this ties all the other parts together when the user types of URL or clicks on a link it gets sent by the URL script that we saw earlier to the view script which then gets relevant data via the models processes it and passes it into a template which finally gets served up as the page the user sees and I don't worry about templates we'll take a look at those later they're actually the easiest part they're just HTML so let's define our models now and then we can move on to working with the views right so we've changed to our project folder and you can see the blog app is here so we'll open that and then define our models which means we need to edit this file so open that up in your text editor or IDE of choice and we'll see what we've got there okay so it's a pretty simple boilerplate to start with it imports the models class from the Django framework and then we can define our models here so remember we said we wanted models that represent one table in a database and that's going to be off blog posts and start with we're going to have author post title post content a timestamp for it and we can we can always add more later but that's what we going to have for now so let's go ahead and define those okay so the syntax for defining our models is very simple to create a certain table you create a class with the name of the table you want so if we want a table of posts we can create a class called posts and you'll remember all of this from the previous lesson on object-oriented programming this class actually inherits from the Django models class so it inherits from models dot model and that means it's now a child class and has access to all of the available methods within it okay and then within it we just assign a load of variables to be all of our different fields so our first field can be author and we set that equal to a certain class which is models dot char field now there are lots of other types of fields for example if it was a number it'd be models dot integer field but this is a string it's going to be a string of characters that represents the name so the moment we're going to go for char field and it has to have a property which is the maximum length it can accept some other ones but it's the only required one and it's good to choose a suitable number of characters for an author's name how maybe not when people have a name longer than 30 so we'll say max length equals 30 characters and that's all you need to do you may have a field for the author of the post and we will create one for the title we'll say title equals models dot char field and we'll set the max length to 100 for this one okay so let's create another one called the body text which will contain the main text of the blogpost so we'll say body text equals models and this one is going to be a text field because just a few characters isn't enough for obviously a whole blog post so we're going to create one that can accept a large amount of text so we'll call this one it's going to be text field and this one doesn't need to take any options and then finally we are going to have a time stamp so we'll say time stamp equals models dot gate time field and this doesn't need to take any options either now if you remember back to the third lesson when we were working with the different modules you remember we can use the date/time module to convert these date/time objects into strings which is what we'll do when we create the website so we'll have a number of milliseconds representing the time and then we'll convert that into a string with the current time this gets displayed on the page so we've got our models here but these are just a description of the type of data we've got and we need to make an actual database from them however first we need a database running and we're going to use MySQL on an actual web server this wouldn't be a problem because they always have it pre-installed but with a package manager it's very easy to install in your system okay so let's open up the terminal and install MySQL just use any package manager to do it if you're on Mac then you probably want to install homebrew and I'll put a link to the download instructions for that in the text of this tutorial if you're on any Linux system not be a package manager included with your system so let's install MySQL now I'll just put a type brew install and MySQL and actually do everything for us so we just wait for all of this process to finish so that took about three minutes so I'm going to edit out a bit of that process there but if everything went successfully you should be at this screen now and it should say that everything was installed okay so now that we've got django installed and mysql as our database there's just one final thing we need to install to finish off and that is the python library for interfacing with mysql just called MySQL DB and we're going to install that using a different pack manager to home brew because homebrew doesn't have it in its default set of available packages so we're going use something called easy install and I'll put a link on how to get that set up on your system in the text of the article along with all the others but once you've got it install you just need to type easy install and then the package we want is MySQL Python now I already have it installed so it won't give me a message for all the installation process but it should for you if you haven't got it already so we'll run through that now you should have the mysql Python library installed on your system so that's all the software we actually need so now we need to try and run MySQL so that we can can interface with databases on it so the first thing you need to do is run the MySQL server which you can do just by running MySQL D and that should start the server running so we've got MySQL installed and running but by default it comes with a user called root with no password and that's not very safe so we need to do something about that so we'll open up a new tab and we need to log in to MySQL with our root user so we're going to do MySQL the username - u is root and then for you that should be fine all you need to do is hit enter however I've already set up a password for my root user so I need to enter my password so I will I'll put the dash P thing - to prompt it for the password and then it'll ask me for the password I chose which for this tutorial I just chose an A+ so that should be fine and now we're in the MySQL prompt now obviously you would have been able to log in without the password and you don't currently have one so we need to set a password for this user and for this we can just use a simple command so we're going to give give ourselves a root password so I'll just paste this command in and this is just a MySQL command to manage the user so I'm giving our root user a password of net tuts and you can choose a password of whatever you like but this will do for now this is what we're going to use as the example for the rest of the rest of the tutorial so I will do that and then you just need to run a command to make sure this takes effect sorry I spelt that wrong okay and now we should be all set up with our with our root user and a safe password so now we can create the database for our blog okay so now you should have a user with a password so we need to log out and log back in again with our new password so we're just going to quit and then we're going to run the same command again but this time you will have to put in a password obviously I had to before but that's just because I was already set up so then we put in the password and now we're logged in running with a user with a password and we're ready to create the database so let's create a database let's type create database and we will call it first block if this doesn't work for me it's because I've already made one but this should work for you if you've got nothing installed yet so there we go says the database exists but that should be fine that should all work for you and we now have a database called first block okay and we can quit out again this is all we need to do for our Django project to be able to run so let's go now and have a go running our Django project okay now a new tab and it changed my documents directory and then change into the first blog folder we made and I'm going to try and run our Django server so the thing you need to know about this is this is not the final Django server this is a development server and it's built into Django and it allows you to test your code when you're still working on your project it's not a very powerful server and it means when you go into production you don't want to be using it so make sure you're not using this technique to run your finished website we're just going to use it now for development and to use it it's as simple as invoking Python and there is one little one little detail here the library we installed for interfacing with MySQL has probably installed to Python 2.6 and as we know from the first lesson we upgraded to Python 2.7 so this isn't going to work if we just type Python we need to use an older version just for this just for this one script so we're going to use Python 2.6 we're going to use the manage PI script that we saw earlier in the lesson and we're going to pass it the command run server to run our basic django server now this will probably give us an error but we'll see what happens okay we've got a problem we haven't set up our django project to work with our mysql database yet so we need to go and fix that now so if you go to the your project directory and find settings pi open it up in a text editor you should see this now if you scroll down to where it says databases we need to configure it for what we just set up so if you remember the name of the database was first blog one we just went and created one just a few minutes ago our username was root and the password is whatever you set it to be I set it to be net touch okay and the final thing we need to do is make sure that it's using the MySQL back-end because you can use lots of different things you can see you can use sequel Lite or Oracle SQL so we just need to change that to be MySQL and that should actually have a quote there so that's just a problem with my one that's not something you should have to worry about okay so once you've got it set up with all of your settings we'll save that and let's have another go at running our script okay that's great we've got our django project running on the development server with no errors so in future when you want to run your development server you just need to run this one command so you just need to do Python 2.6 manage pi run server that's all you need to do however when you start up your computer the MySQL process probably won't be running so if you remember earlier we just typed MySQL D to get that running you might need to do that first so that it runs and then you can run the Django server you could actually set it up so that my SQL runs every time you turn your computer on but a lot of times you'll be using it and you won't even need MySQL so that's a bit wasteful of resources so that's not something we're going to do today but it is an option if you are doing Django development every single day but anyway you just need to know that if it doesn't work the most likely problem is you need to start MySQL by typing MySQL D so anyway with that all out of the way we can go and check out our running server so as you can see we can find it at this address which is the localhost IP and it's running on port 8000 so we can open up our browser and go to this address and we will refresh the page and there we go we've got our very first django powered page as it says so all that's left to do now is customize it and turn it into our own website with all our blog functionality so let's take a look at how we do that now now your process to get to this point might not have run quite as smoothly and if you do run into any errors with any of the software we're using to install or configure this this particular Django installation then please leave a message in the comments and I'll do my best to help you out but in all honesty there are so many different things that can go wrong with it probably your best bet is just doing a quick search for whatever error comes up and and working from there but yeah like I said if if there's anything you do want to ask about then I will do my best to answer it that in the comments so we don't need the server right now we can stop it while we do a bit more development on our site and the next step is to set up the tables within the database we've created using the models we defined earlier so just start ctrl C and and then we need to run a command which will add all of the models that we created to the database and if you don't remember the models were those fields for all things to do with our block so we had an author of the post the title the body text and the timestamp so these is just a description at the moment and we need that to actually be tables in the database not just this abstract representation of it so there's a command we can run for that and again it uses manage PI so we can run Python and we can use 2.6 and then we will use manage pi and this time we are going to run sync dB and that will add all of the fields defined in the models to our database every time you update your models you need to run this command so that the new field you've added get added to the database however it's important to note that this can't actually alter existing records in the database it can only add new ones so if you need to change one of the fields for example you've got an integer field and you need it to be a varchar or something like that then you will have to actually go into something like PHP myadmin alter your MySQL table yourself and then update the models file to reflect that and then obviously run the sync DB command again to make sure that they all match up but yeah this is the command you'll be using every time you change your models to update the database so I'll run this now and update our database okay so because this is the first time we've run the command it's adding additional stuff as well as the models we define for our blog it's adding all of the default stuff that lots of sites use that comes with Django for example it's adding all of the authentication tables it needs and everything and for that it needs a administrator user so we're gonna have to create one so we'll just put yes and then we can have the username as whatever you like it'll probably come up as your username by default so I'll just go with I'll just go with the yeah Giles is fine for now and then you can put in an email address so that it's I guess in a production site this so you can be contacted and stuff so we don't really need to do this for this we'll just hit some characters there we go and then choose a password I'll use net touch again this time and there we go that's all run it's all run correctly and hopefully you didn't get any errors either so now all of these all of these models we can see here these four fields they've all been added into our database and they're ready to be used to store some data so finally we are actually ready to start working on the logic and structure of our site okay so let's take a look at the files we've got so far we've got our URLs file which as we learnt earlier except the incoming requests for a particular URL and tells it which page to serve up so let's see what we've got in that at the moment okay we do actually have any URL pattern so what we need to do is to start we need to set it up so that when a request comes in for the root directory of the site it serves up our home page our index.html file and in fact this default line here will do that nicely so we just uncomment that line and this will this particular regular expression redirect the any root directory request to this model we define here this isn't actually right because if remember it's called first blog but the module within it is actually called it's called blog so we need to we need to change that to be first blog blog so that's our project and then our model and then we go into the views file which is where we'll respond to this request and then we're going to call it home and we'll give them a name of home so we've got our we've got our very first request there and now we can actually serve up some content but so we'll go and look at the views file and make this request actually do something so go into the blog package and open up view spy okay and as you can see we've got a completely blank file so it's up to us to create all of the code here so the first thing we need to do is import the module that's used to render out the response to the pages so we're going to say from Django dot shortcuts is the module we are going to import and then the particular function we need is render to response so that is the module we need for actually for responding to all these requests okay then we need to import those models we define so that we can actually interface with our database and add and retrieve data so we're going to go from our it with surf blog module and it's the models file we're going to import let's see what the particular table is called a case called posts so from our models file we're going to import posts ok and now we need to define a function to respond to this request so we can define a function and it's the same name as whatever the request was and remember the name was home so we're going to define a home request and this particular function takes the request argument that gets passed to it when it gets called and then we need to return a particular page so we're going to return and we're going to use this render to response method to render our particular template so we're going to render to response and we're going to return index.html for now that doesn't exist but that's the next step we will create that so that should be all the code you need to serve up your first page however the page we're serving up doesn't actually exist yet so we'll save this out and go and create it and then see what happens so within our blog app we'll create a new directory called templates and we're going to put some HTML files in there which you can serve up so we'll just create a new folder and call that templates okay nice create the index dot HTML file it's going to be served up so we'll make a new file and I'm just going to put HelloWorld because that's all we need to test if it works and then we'll save that out go into first blog blog templates and then save it as index and then choose a HTML file as the type surged find that there okay and we can save that out alright and let's go into templates we've got the file we need as chosen HTML for the extension HTM for the extension so we'll change that to HTML okay so we should now everything we need URLs we get a request for the root directory that sends a request to something with the name of home then we respond to this home request by rendering out the index.html page that we see here so that should be all the steps we need so we just need to start the server again go back to this and then go back to the run server command run that and then let's open our browser and see what happens there could be some errors but maybe work first time okay so we've got an error and what's this saying I can't find the index.html file okay now the reason for this error is that we haven't actually told Django where to look for our templates yet so we need to go into the settings file and fix that so if we go back to settings we should go down to the bottom and you should see something which says template directories so here we can put the ring upon the path that it serves up our all our templates from and if you remember we put our templates folder as being in the blog app so it's going to be in blog slash templates which one the Nick what we named the folder so that's all you need to put just a string that defines where to look for the templates so we can save that out and then go and look at the page now okay and we've got a hello world which is coming from our index dot HTML so we've got Django to serve up our first custom page okay so we've got our first page set up let's add some actual blog content so we need to go to our template file for that and I guess the first thing to do would be to just put in some boilerplate html5 code so that we've got the basic structure of our website so I'm just going to go and copy and paste it in but you know you can grab it from anywhere write it yourself or you maybe used something like the html5 boilerplate you can use whatever you like but we've just got a basic html5 structure and yeah let's start laying out our site so this is now this is Python at moment this is all HTML so on the title we'll just call it we're calling your first blog at the moment and then I guess within the container we're going to want a header and then this is going to say first blog and then we're going to want a we're going to want a list of posts so for each of those posts we will have a title and we're going to put that in heading two tags so that'll be the title and then I guess we will say we'll say the author and the timestamp then so if we put if we put in in h3 tags below that we can put may be posted on and then we'll put the date in here post it on date by and then author now obviously they need to be swapped in for the actual names but we will we'll work on that in a second we're just laying at the basic structure for the moment so then we'll close h3 tag and then we'll have a paragraph tag where we will put our body text now obviously we're going to want to have this format multiple times once for each post but we're not going to write it out each time we can actually use Django's templating language to put Python code within this HTML document and then use a for loop to print out lots of them but that's all that's all we need to do for now so save that out and that's fine and then let's go and see if that's updated perfectly okay so that's all that's all worked fine okay so we need to actually get the data from our database into this into this template so how do we do that well with Django you can embed variables straight into your HTML documents so you do it with with the following syntax you use two curly brackets and then you wrap your variable name so what we'll have here is we will have a variable called date wrapped in two curly brackets like that and the same for author so we'll do that again and that means we can now use this views file to pass in author and date variables and they should get displayed there so I guess we will want to do the same for title and I guess we'll use lower case variable names and then the same for body text I guess so let's call that body so let's see how we pass in variables first and we won't actually work on getting them out of the database just to begin with we'll just pass in some strings just to test if we've got this bit working so let's go to views dot a and work on that now now the way we do this is this render to response method can actually take a second argument which is a Python dictionary of variables if you've p8 PHP then a dictionary is just like an associative array so it's not too difficult to think about at all we just need to pass in a second argument and we use curly braces for the dictionary and then it's just a set of key value pairs so what we had our variable called title and that contain the title so we can say that title and then you put a colon and then the data you want so our data is going to be my first Pope's will have that for now and that should all work fine so let's save that and test if it works and we might get an error because we haven't specified all the variables okay so we don't get an error it just echoes out my first post and all the other ones are just left blank because the variables don't have any value but that's a good start we're managing to pass variables into our template from our views thing if we add lots of variables this lines going to get a bit long so we should we should structure it a bit let's say that let's say that content equals this dictionary here and then we pass it in as a content variable and then we can separate this onto multiple lines this is just for it's just to keep the syntax nice and tidy so we can indent that and then you'll see you have to separate each one with a comma so the other data we had was author and we can just say that that is pick a name you can use your name if you like and then date now in a minute we will work with the database and we will make it retrieve a timestamp which will be a number and we'll use pythons date/time class to format it into a string right here but for now let's just pass in a date so we will say that date is also the date is today so the LT of September 2011 okay and then the final one we had was the body text so we will say body and let's just put in some lorem ipsum so I'll go grab some off the internet okay there we go we've got some default lorem ipsum text so that should be all we need to set up this side so let's go and have another look again refresh the page and there we go it's all working we've got our title and then we've got the post title it's accepting the date it's accepting a username and it's accepting body texts so on a very fundamental level this is all the blog is however without dynamic content it's not really a blog at all so we need to go and hook up to the database and start querying some data to display here instead so if you remember to retrieve data from the database we don't actually have to write any SQL queries at all because Django abstract all of this for us through its models so we need to go take a look at though now and work out how we can get this set up there's a few things we need to do and the first thing is a settings configuration now we haven't actually imported the app to our project yet it's not actually using it so our first blog project needs to use our blog app so it can access all of the models that it defines to get this set up is very easy you just need to scroll down to the installed apps section of the settings file and then add a string to the list which defines the app that we want to import and in our case that app is first blog name of our project blog which is the name of our app okay so now we've added that let's go look at the views file as you can see we've already imported this posts model earlier which represents the table in our database but we haven't actually used it yet and we can use it for both retrieving data and saving data so let's take a look at the syntax for retrieving data now posts represents the table and the first thing we need to do is type posts janggo returns all of the data from the database in a special structure called a query set which is iterable which means you can use a for-loop to access all the properties and go through it the root query set is called object and from that you can access all other query sets beneath it so we need to type objects and then we can finally start to access individual properties of the database now in this case we're just going to access everything and for that you just type all and that's actually a method so you need to have the parentheses there and that will return everything in the database there's also a method called filter which lets you pass in some arguments and specify certain parameters like in MySQL there's the where statement which lets you say where x equals y and that limits it to only records where that is true and in this case you can do that with the filter method as well but in this case we just want all the posts that have been added to the database now there's a really nice feature here and that is a slice syntax just the same as array and string slices in Python and it lets you limit the number of queries with the square bracket notation so in our case maybe we just want our default home page to display the the 10 most recent posts we can just use a slice it like any other array or string and put : 10 and that will access the first 10 posts so that's really nice and it's got all of the features of python slicing syntax so if you wanted to access just the tenth element you could do that and if you want it to go only from five to ten you could do that but for now we'll just we'll select the first ten so that if we have you know hundreds of posts in our database we don't end up putting them all on the home page so this object now represents the first ten records in our database and obviously we need to assign it to a variable so let's just call that post the next thing we need to do is pass this posts query set into our template so that we can access the data within it so we don't need any of this anymore this was just an example so we can get rid of that and then we need to pass in a dictionary here and we can just say that posts is our posts variable and then just curly braket to close that and that should mean that this posts variable gets passed into our template for use over there so let's go look at the template now and look at how we can implement it okay so at the moment we are hard coding these this blog post but what we really want to do is iterate through this query set get each record and display all the relevant data like the title the date and the author to do that we need to look at another part of Django's templating language so you can see here we've got variables with the two curly brackets but there's also something called block tags which has a curly bracket and a percentage sign and what that allows you to do is put Python code within this template for example we can have if statements and for loops or within our template so let's go ahead and add one now and we don't want to add one around the title because there's only one of those but around all of this we want to add a for statement so we're going to put a curly brace and then percentage sign and then you close it out the same way centage signed curly brace and within here we can actually put Python code so what we're going to do is iterate through this variable that's been passed through and the variables called posts so we can just go for post in posts and then every time we iterate through this array post will represent one record now usually you'd have a colon here in a regular Python but because we're using this slightly different syntax in the templating language we don't need to so we can just leave it like that and another difference is because it's not regular Python it doesn't know where this ends so we actually have to put something which Python doesn't usually have and that is end for so Django's templating language knows where to stop this block and let's just let's just indent all of that just to make things a little bit clearer to read so every time we iterate through this post represents one of the entries in the database and we can use properties of that to access the individual fields so the field names are defined here back in our models we've got author title body text and timestamp so we can say post dot title and then that will give us the title of the post and we can do the same for author we can put that there now it's calling this date before but we've got it as timestamp so I'll I'll update it to say that I want a post timestamp and then finally post body text and that should be everything we need to retrieve data from the database we've imported our app with the settings and then we are accessing the models here we're getting all of the data out of the database and then selecting the first ten records then passing it to the template looping through it and echoing it out each time so let's go ahead and preview that now okay we've got an error so let's take a look and see what's gone wrong it says the posts is referenced before assignment and that's on line 6 so we'll go and look at that now ok yeah the problem here is that I've got the same name for the module as I'm using for this Barrett variable so let's call it something else instead let's call it entries and then we will change that down here to say entries and that should work now so let's go back and refresh the page okay this is working we've got a proper dynamic blog we are retrieving this data from a MySQL database and then looping through it and echoing it all out onto the page now you won't be seeing any of this and you may even be getting an error and that's because I've done a little bit of work beforehand currently this posts table that you're trying to access is empty because we haven't actually added any data to it yet and I've been through earlier and added some sample data but that's very easy to do so we'll go and do that now so you can actually see what the finished product looks like so there's a couple of things we need to do and the first thing to do is to run the sync DB command again because what we did is we went to the we went to the installed apps and added this blog one which means that now if we run sync DB our blog table should get added to the database so let's just stop the server for a second and then we can run sync DB and for you it should say that it's adding your blog model to the database so I won't get that but for you that should happen and then once that's worked we have the table in the database and all we need to do is add some data to it so we can actually go to a MySQL prompt and do that and this is what I've done earlier I've just written this MySQL query that inserts the data into the database now you don't have to understand MySQL and I will put this command in the text of the tutorial so you can just paste it in if you want but the syntax is very simple and all you need to do is run it once or twice I'll just run it once more and there we go we've added another row and if we refresh it again we should now see we've got three and of course we need to run the server so we'll go back to that and run server and we should have three posts now yeah there we go we've got three so if you want to run that MySQL command a few times you should have some dynamic content which means you've got a properly functioning blog system now obviously to do this you need to be in a MySQL prompt and if for some reason you closed out of it or whatever then you just need to type MySQL and then log in with your user and make that root and then put - P - be prompted for a password and then we just put the password as net touch you may have done something different and then you should be in a prompt which will let you which will let you run all these commands you could just type my SQL but then you're not a root and you might have permission to to add things so yeah remember to run that command and then you'll be in a MySQL prompt and you can do all of that so before we go any further let's just add a little bit of structure to our page and we're going back to HTML here but really every post should be in a div tag so we'll just say div class equals post we have any styling attached to this yet but you know just to make it semantically correct and then we will close out our div tag here and then we should have maybe a horizontal rule after it just to separate all the posts and then maybe another one of those after the after the title so that that just done makes everything a bit easier to read so if we refresh that now that is looking a little bit nicer now okay so the last thing we need to do today is take a look at Django's admin section and how we can use it to manage our new blog now this is one of the great advantages of Django this is another thing where a lot of works been done for you it all comes with it and it saves you a lot of time if you were writing this from scratch you'd have to create your own management system for publishing to the blog but with Django there's a really powerful admin interface that does all that work for you so let's look at how to set it up now it's pretty easy you just need to change a few settings the first thing we need to do is go to the URLs file and there's just some lines we can uncomment this one and this one and these two down here and that just means that when we type in slash admin we go to the admin file ok after that we need to go to the settings file and uncomment these two lines here in the installed apps section and these will add the admin apps to our project so just save that and then the last thing you need to do is go to the terminal and just quit the server and if you run sync DB again it will add all of the necessary tables to your database that the admin section needs so just run that and you should see some stuff pop up there for installing all the tables ok and then let's just run the server again and then let's go and check out our app in ok it should be at the regular URL but with slash admin if we just refresh the page so we're presented with this login page and the details to log in are the ones we chose earlier by default I think it's the name of the user on your system and then the password I went for net tux but you need to put in whatever you put obviously and then we just click login and you can do a load of stuff with this interface it's really powerful but today we're just going to look at how can use it to add content to our blog and it's pretty easy so to do that we need to go back to our text editor and then I've created a file called admin PI and this is in the first blog project in the blog subdirectory so you need it along with all the others the admin file is just right there and within this we need to import the admin and our posts table and then register the post table with the admin so it has access to it so we need to say from Django dot contrib we're going to import the admin module and then we need to copy this line from the views file where we're importing the posts table and then we're going to put that in there and then finally we just need to register it so we type admin dot site dot register and then we pass in our posts model as an argument okay so if we save that and reload the server we should see that we've got access to the posts table within the admin section so let's open the terminal and then we just quit the server and run it again and refresh this page okay and now you can see this has added it we've got our posts table right here so if we click on that you should see this represents the one thing in our table so we've got this one this one blog entry here and that is represented by this one entry and if we click on it Django's created this nice editing interface and it's got some nice features the interface is based on what types of fields you've got so if you've got a VAR chart field you get this little text box here if you've got a text field you'll get a much bigger one we've got a date/time field and then we get automatic controls for putting in dates and times so it's pretty nice and it saves you a lot of work so let's give our post a timestamp because at the moment it's none because we didn't enter anything so we can just do today and now and then we can just save that and we'll see it's all happened successfully so if we refresh we've now got a publishing date and we can add another thing to our blog we can say this one is by Jo set the title as news or something then maybe put some lorem ipsum in there and we'll set that to today and now as well if we save that and refresh the page there we go we've got the new post in there so there you have it if you've got to this stage you've just created your first django website and we've got a fully functioning blog with a control panel where you can add new content and a home page where it's all displayed and obviously another time we could go and add a comment system or individual pages for each post but now that we've covered getting django running locally and we've written the basic site with it we should finish off by talking about installing it on a server now there are two types of web hosting and which one you have will affect whether you can use django if you have shared hosting then you're entirely at the mercy of your hosts a lot of cheap hosting won't support Python and while PHP is almost guaranteed support for other languages often isn't you'll have to check the control panel to see if Python and therefore Django are available now almost all hosting runs on Apache and it has some modules that we can use the host django and these are mod WSGI or mod Python most web hosts also that you run scripts in several languages using CGI django can run on fast cgi and also theoretically on regular cgi but it's not officially supported and it will be far too slow for an actual production site you'll need to check if these are installed they usually found under a heading like CGI scripting and language support now unfortunately I don't have any shared hosting so I can't show you examples of this today but if you search around then you should be able to find some guides on getting this set up on whatever hosting company or server you've got now if you have VBS hosting or are even lucky enough to have a dedicated server your life is much easier these usually come with Python pre-installed because they're running a Linux distribution and they always have Python and you only have to then follow the same steps we went through just now to get a local copy of django running if you don't have python you can install it with a package manager and your system may even come with Django I'll quickly run through it now on my VPS but the process is very similar to what we did earlier so I'm going to open up the terminal and then create a new tab and then I'm just going to SSH to my site so I'm going to SSH root of my site all right so now we're at the prompt of the remote machine it's pretty much the same process as we went through earlier in the lesson we just need to download the latest Django release so we type W get and then go to the Django download site and then just copy this and paste that in okay and once that download is completed we just need to use tar and then we use X Z V F options to extract it and then we're just going to type in the file name and it appears to have called it funny named index.html got one for some reason so we just have to type that and then it should extract all that to a file and we can CD into that folder and then we just need to run Python setup buy and install and there we go we've got Django installed on our system and now to test it all we need to do is enter our Python prompt and we can say from Django import get version and then we just need to type get version and we should see 1.3.1 and there we go we've got a running version of Django on our remote server so let's try uploading this project to the server and running it from there now I'm using cyberduck here but you can use any file transfer client that you like and I've just logged into my server and this is the root directory and I'm going to put my project files in the home folder you can put them any way you like but don't put them in the document root because then they'll be publicly available everyone can see the source of your website and and that opens up security issues and stuff so yeah just keep them in any private folder on your server I'm gonna use home ok so I'm just going to grab the entire project and then drag it and wait for it to upload okay when that's finished let's move to the terminal and work on getting it running there's going to be a few issues because the settings are slightly different on my website as they are my local machine so it's not going to run the first time but we can see what happens so the first thing you need to do is try and add all the models to the MySQL server by running the sync DB command so we'll navigate to the project directory so the first thing to do is to change into the folder we just created so I'm going a CD into home and then first blog and then we're going to try and run the sync DB command to add all of our posts to the database it's not going to work but we can at least see what the error is so we need to do Python and then manage PI and then sync DB and the error we're getting here is that the password is wrong and that's because we're using the password net tuts for the local machine and obviously on my server that's different so go ahead and update those settings now okay so once you've changed your password let's have another go we probably going to run into more errors but we'll see okay so we've got rid of the password error and now it's saying it doesn't know which database we're trying to connect to and that's obviously because the MySQL instance on my server doesn't have the first blog database so we can enter the MySQL prompt and as the user root and then it'll ask for a password and then we can create this database so we just say create database and then I'm going to call it first block just like we did locally okay that should be done so if we quit out of that let's have another go and this time it's worked so we can go through all of this process for setting up all of the admin stuff like we did before and then once you've entered all that we should be able to run the server so we can just type Python manage pi then run server if you just run this command it'll run Django locally and then you will be able to access it from the internet so we need to specify an IP address and it's just going to be all zeros and then run it on port 8000 so that we can access it from anywhere not just on the server itself so we can run that and we appear to have got everything working so it's running so we can go and visit it at port 8000 of my site okay and then in new tab I have visited my site at port 8000 and we've got our django server running if we visit the admin page that works - and i can type in a username and password and we've got all the same stuff available to us including the control panel for adding blogs so we can add posts just like before and then if we go back to the regular site we can see that the post has been added so today we have learnt how to create websites with Python using the Django web framework and we've learned how to install it on a local machine and on a remote server and server web pages including dynamic content from a database and managing it all with the admin system as always I'll be happy to discuss any questions about this tutorial or Python in general in the comments and always visit net touch + comm for the best web development tutorials around thank you so much for watching I'm Giles LaValle
Info
Channel: Tuts+ Code
Views: 845,765
Rating: undefined out of 5
Keywords: python, python from scratch, nettuts, web development, programming
Id: bRnm8f6Wavk
Channel Id: undefined
Length: 59min 57sec (3597 seconds)
Published: Sat Nov 19 2011
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.