Python Web Development: Understanding Django for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Thank you for this video, realy like it :-)

๐Ÿ‘๏ธŽ︎ 2 ๐Ÿ‘ค๏ธŽ︎ u/m3tamantra ๐Ÿ“…๏ธŽ︎ Nov 15 2013 ๐Ÿ—ซ︎ replies

I'm trying to follow this. I think it is old, or I am just not very good at doing this. Both are certainly possible.

๐Ÿ‘๏ธŽ︎ 1 ๐Ÿ‘ค๏ธŽ︎ u/tothelight ๐Ÿ“…๏ธŽ︎ Nov 14 2013 ๐Ÿ—ซ︎ replies
Captions
[Music] my name is Simeon Franklin I am a longtime software developer I've done mostly Python and Django stuff for the last mmm five or six years but I quit being an honest developer about a year ago in started to work full-time for a company called maracanรฃ so I I now train for a living I teach people Python and Django and occasionally bits and pieces of JavaScript mostly as penance for my sins but I've been lots of interesting places talk to lots of interesting developers I was at Facebook last week I've been to Intel and Cisco and Motorola and Qualcomm you name it been there and if you're interested in the stuff that I'm interested in hey follow me on twitter SME and franklin hit up my blog ID right there you regularly come find me in the Python community SF Python meetup in SF is a lot of fun we meet at Yelp there's beer and pizza and interesting speakers or come down to Bay Piggy's in the South Bay if that floats your boat and I sometimes go to the django meetup in SF as well don't organize that one um but you know you might catch me there from time to time and remind me at the end of the talk to talk more about the wonderful Python community so this talk so I aimed it for a novice audience for people that don't have experience with Django and I'm hoping to like let's you feel like you understand an overview how Django works the minimum number of like concepts and terminology you need to write web applications with Django I want to show you some of my favorite third-party django apps that turns out to be a lot of what acquiring experience with django involves and then just close off with if your experience with django you know some python and you're bored with the first two thirds of the talks we'll talk about some advanced python language features that you ought to be using and how you can use them with django and you know throw some code on the board and see if there's anything that makes us stop and think a little bit and I have no idea how I'm gonna do on time here so I'm a I'm a race or jump ahead or I may end with twenty minutes for Q&A and it would be awesome just in terms of the talk in general feel free to ask questions you can interrupt me that's right if you don't understand something if I'm going too fast raise your hand throw something in my general direction I might throw it back at you just you know no heckling so let's talk about let's talk about django django is a web application framework I need to talk about what that means exactly but it's been around for a while it was first released in 2005 it's kind of a a project that was abstracted from a particular web application made for a newspaper in Lawrence Kansas and it had some immediate popularity it just it just hit things exactly right a web framework written in Python Ruby on Rails was hugely becoming hugely popular right at that time and Django is kind of pythons answered Ruby on Rails so tons of development activity tons of revisions it didn't have kind of a good formal release cycle until 1.0 in 2008 three years later but had tons of community participation and Django 1.0 is kind of more or less modern Django it just released 1.5 earlier this year and Django is kind of on a six-month release schedule they promised to come out with a new version every six months as a matter of fact they always slipped by a few weeks but the the release cycle has been been good for us so with a web framework it's kind of the same space as competitors Patricia mentioned like Ruby on Rails or maybe heard of pyramid or nodejs and JavaScript or or other Python things like flask PHP stuff cake PHP code igniter just the general space is to write quickly write web applications that are backed by a database and a Django I'm not sure how to convey its popularity it's been successfully use on really large projects so discuss the internet commenting framework you can have discussed comments you know on your blog it's a huge site huge traffic site has been written in in Django forever David Kramer the the discus guy has contribute a lot of performance stuff the Django core and Pinterest maybe know about Pinterest tons of pictures of social media around pictures cite the onion first parts of mozilla.org that have to do with collecting data back from the millions of Firefox browsers so jank has been used for lots of large and successful projects as far as numbers like if you look at pi pi which is the way you can automatically install Python packages Django version 1.5 had 50,000 plus downloads and it was released in February so it's being actively used there's a site called Django site org that's supposed to list a lot of sites that use Django it has 4,200 sites listed I can promise you it's not exhaustive because like I've written 100 sites that aren't on there at all but it's it's widely used I did think I'd try some Google Trends to show Django being popular but um screw you Django Unchained he just totally messed up our search keywords so this graph is completely meaningless paying no attention to it at all but but it is popular it is widely used it is kind of beloved in the Python community why Django why might you pick Django it's interesting one of the reasons to use Django might be a reason that frustrates you a little bit Jake is a project that has paid a lot of attention to documentation from day one the guys that started it right worked for a newspaper some of them had English degrees instead of CS degrees they were around writers they valued good clear Thoreau comprehensive documentation so Jago had great Docs it still does there's a lot of them you might have noticed another reason to pick Django is Python so if you're like me you love the Python programming language maybe you have a half a dozen languages to compare it to maybe is your first programming language but I can assure you Python program Python makes me happy happier than happier than C C++ Java Perl most other stuff that I've written code in anger visual basic way back when Delphi there are lots of old musty language rattling around in my brain but kind of the other reason for Django the why Django question is Django is a full stack framework or you might say its batteries included so Jenko does like everything almost lots of competitors in this space are frameworks that aim to provide you a minimal core that you'll extend to do your thing Django tries to give you tools to do everything you could possibly want to do it does a really good job at that it turns out that it's not enough and we'll look at that in a little bit but jenker just kind of hits the sweet spot for the typical kind of database backed web applications that kind of make up 80% of the web applications people have written for the last the last half a decade or so makes a lot of that stuff easier faster you could check out the docs you've probably been to docs Django project com take a look at the front page there's a lot of links and if you're gonna be a Jenga developer yeah you kind of have to read all those links on the front page it's good ducks they're comprehensive they're they're well organized there's tables of contents there's a good search engine and really the whole framework is documented there aren't very many undocumented bits and pieces laying about and it's traditionally had a tutorial which is most people's first exposure to Django so quick show of hands who's done the Django tutorial did you do it for version 1.5 out of curiosity so now it has like five sections and some extra sections okay the latest version maybe so do start with the tutorial that's that's still good advice go take the Django tutorial it'll walk you through some basic concepts especially it up to version 1.5 it did some dumb things but I think make it harder for you getting started and I'm hoping in this talk just to give you a different introduction to Django the the basic moving pieces that you need to know I still do the tutorial if you haven't but it might go better after this talk so let's just look at the fundamental like the concepts the terminology you need a master to write web applications with Django and we'll do that with a really really basic web application so you want to build a web application with Django what does that look like might look like Pinterest people have been there right big front page with lots of pictures people make accounts people pinned their favorite pictures you can follow people and see the things that they pinned there's lots of data flowing around lots of dynamic data or you know maybe your interest is reddit another social networking site pretty much oriented around I'll post a comment or I'll post a link to an article and then everybody will comment maybe you'll vote me up if my comments are particularly insightful it's almost like a game right acquiring some score but again there's lots of data there's people relationships points articles comments lots of data floating around so those are two really different projects but they're both kind of the sort of thing that you might try and do with Django their HTML interfaces too highly dynamic data with a relational database back-end it's the kind of thing that the Django is really good at so what do you have to know to write the next Pinterest well that's gonna be more than this but let's start with this so the first bit is just that Django is going to be HTTP in and HTTP out it's gonna hide that from you a little bit but you're gonna need to understand that so the the diagram here has HTTP requests and HTTP responses and Django is the stuff in yellow the minimum that you need to know to write a web application is you need to know about URLs URLs and Django are basically how you say hey the request that's coming in where should it go and you pick something you gotta know about views views are gonna be the Python color balls that actually return a response and if you have a really basic web application your view might only use models to talk to the database and templates to produce some HTML so let's see if we can understand like this much and again write a really simple trivial web app with that amount of understanding I'm gonna kind of wave my hands at the installation section go see the documentation but if you know Python tools you can make a virtual environment you can use pip to install Django and then there's a couple of concepts you need to know once you have Django actually installed the first concept is a project so your web application just let's call that a project the web application is a project and Django comes with a tool to create a project for you kind of a blank empty skeleton of a project so once you have Django installed you can type a command called Django admin dot py and it takes sub commands and the sub command that you're interested in at the moment is called start project and you can give your project whatever name you like as long as the valid Python identifier so don't go crazy with spaces or weird characters stick the alphanumeric and underscore so I said Django admin start project story time and then just to see what files I got I got a new directory called story time I've got some settings URLs and a managed up py in there there's a couple of other files we pretty much own how to pay attention to there's a whiskey file that's kind of about your deployment and there's an init file - uses what's the init file there for the file it says underscore underscore init underscore underscore dot py there you go so that files empty its sizes zero it has no code but that's the special file Python looks at to say can I import this directory as a module or not so little Python thing there so what does the project have fundamentally that we're interested in the main thing it has is settings so the settings dot py basically says like okay which project is this maybe things like what database you're going to talk to or who are the users who can use it and what what all the configuration details for your particular application are there's a manage that py file there you won't ever edit edit the manage py file it's just a command runner as to do things in the context of your project you will be editing that settings and then there's a URLs dot py file and this is your starting point to configure your URLs which is the very first thing that you need to do so everybody with me so far I ran Django admin I started a project I haven't edited any files whatsoever yet I have a directory full of Python files I didn't create them they've got lots of sensible defaults and comments we can use that manage py file to then run commands from now on you could still use Django admin but manage people I knows what at what project it's in so the convention is Python manage that py and then some kind of command the first command I want to try out is run server and run server is a development web server it's not something you should use in in a production but it does let you point your web browser at your own IP and some weird port it's usually 8000 by default you can customize that if you want and see a webpage if you have a webpage so did we make a web page well sort of it works congratulations on your first django powered page we haven't done anything yet except to successfully install the framework so it has some helpful comments if you plan to use a database edit the database settings in your settings dot py you're probably gonna need an app so run Python manage py startup and then some app name with those things and see what we get so another fundamental piece of terminology web applications in Django are projects and then projects have applications inside them and you actually have a bunch of applications for free from Django and all the development work that you're gonna do mostly is gonna live inside of applications so how could I make an application you might expect from the experience making a project there's a command for that so again I can run Python manage py and command I'm interested in is startup and startup takes an application name and I'm gonna call my application story so I still haven't edited any code at all just generating code with these tools and I get a few more files again just using the find command to show the new directory story that was created inside of my project and a couple of files inside it I have a views dot py there's that an it again I'm just kind of ignore that makes it a module tests and models the the start page that we got before when we started up also hopefully said hey you need to go edit your settings file and you need to specify a database so I said you know database backed web applications you don't have to use a database to use Django but it takes a lot of the point out of it if you're not going to use a data store so SQLite is a little toy database the drivers come with Python so it's a favorite favorite to use for for demos it's um it's not really a database server it's a little you know database in a file you can think like Microsoft Access or FoxPro if you have experience with any of those technologies don't use it on production it's it's not multi-user it's reasonably fast and we can use it to do our little development work so I changed my settings file and said two things the engine that I want to use is Django DB backends sqlite3 and how did I know that particular string they helpfully left a comment with the the possible options I could put there and then the name and in this case the name is just going to be a file that'll be in the current directory for backends I could have chose chosen a lot of other database backends again there's a comment suggesting the other options but whatever your database preference if you've got one Jenga supports it so MySQL PostgreSQL mssql Oracle whatever it'll hook up to it hook up to all of them with only slightly varying degrees of support the other thing I needed to do is what you're going to get used to doing every time you add an app I need to edit my installed apps directive so this is also in my settings py and I just added the little line at the bottom that says story there's a list of the Python import paths to Python modules that are not just Python modules they're also django applications and hey story is the one I just made stories in there just needed to add that and I'm on to the fundamental concepts we got to know about see URLs views models templates okay so URLs the first one fundamental concept number one this is just the part after the domain right you go someplace you've got a domain and then you've also got like the bit in red here foo and all web frameworks are pretty much a way to say well if somebody goes to the path foo what part of your code should I call in response right Django's way of handling that is to have us write regular expressions that match a path that's coming in and then include the view that should go along with that particular regular expression so this is the default URLs py and has a couple of comments it says you could write URLs that look like and then it's kind of hard to read strings and R and a caret story time and a slash it's kind of sucks actually especially for beginners like again quick show of hands who feels really happy with their red X foo and whatever language can do it nobody feels happy right so jamie zawinski code I think I know have a I have a problem I know I use red X's now I have two problems so it kind of stuck so the first thing you have to do is figure out regular expressions and regular expressions are a mini language for matching patterns and you probably know a little bit about it every character more or less is significant you know why do I have to learn this right away one reason is reg X's are fast and they're really flexible if if like the Django he started in a PHP and Apache world this is seems like the sensible way to do things you're used to writing reg X's the map to paths for like Madhuri write in Apache so it just seems like the obvious way to do it it's it's not painful for you you don't know why should be painful for anybody else and let's say for the beginner fortunately for you you can start out by copying and pasting so for us we're just gonna write a single URL and see if we understand the rule so this is my url zui it was automatically generated by the start project and i went in and just put one line of code it had some comments I delete the comments I put in one line of code and that's the bit in the middle that starts with URL and let's let's understand this character by character so python knowledge actually I've got a little piece of code there what's the R for anybody know so it's not a reg X the R thing is Python and it's telling Python that I'm going to type a string and you shouldn't interpret any of the characters inside the string so if you make a string and python normally and you have slash in Python says you don't want to slash and then an you want a single newline character right does a little bit of a character magic for you there's a bunch of things like that the raw string python isn't gonna do any string interpolation on at all and since red X's are full of weird and wacky punctuation it's common to write them with raw strings to make sure that the string you get is a string you typed okay so that's the R and then anybody who does know reg X is what's carrot and then dollar sign mean right so carat is the special syntactical start here in red X's matching a string and dollar is the special end here and I've got nothing between them so I've written a beautiful magical red X it's two characters that basically means I didn't get a path I got nothing the next thing in my url statement is a import path to a django view and we don't know what a view is yet so we'll talk about that in a second for the moment I'll just say it's a Python callable and then the last bit is a name django lets us name our urls naming our urls is really cool because later on instead of hard-coding whatever the particular path might be someplace you can just say hey figure out the path that corresponds to the URL called home it's good practice to get into name all your urls and as usual hey you could go read the Django Docs they're excellent they're comprehensive there's links in the slides I'll post a slide so you can go to the right spot okay URLs that everybody get that we just we said hey if you don't have a path go someplace to something not too much yet right okay so views fundamental concept number two that we need to understand a view is Python code that takes a request object and returns a response object that sounds a lot like what Django does in general you can write in views a bunch of different ways but let's write a really simple one a Python callable well one kind of Python call bow would be a function it takes a request object so that's just a parameter to my function and has to return a response an HTTP response I have no idea how to make an HTTP response unfortunately Django has an HTTP library that will let me give it a string and it'll make an HTTP response which is a bigger thing that's got lots of lots of headers and pieces of data about the response so this is a django view pretty simple right just the function takes a request returns a response and the response says hello world sweet we build a web app right you go to no particular place you know kind of just the domain itself and you see hello world it works we don't have any HTML yet and that's part of what we want to do with Web Apps so concept number three that you got to know is templates and especially when you get started you might spend a lot of your time knowing and understanding templates we want to make a web application we better build response that's got some HTML in it and so there's a common use case here your application probably has a bunch of HTML that doesn't change right you've got like a header and a footer and a menu and then you've got some HTML that does change a lot you know kind of the middle part of your page maybe it's Pinterest in your showing pictures maybe it's reddit and you're showing stories and comments most web frameworks include template engines and they try to let us manage all this HTML in kind of some common ways basically we can put HTML and then some placeholders and the placeholders might be code and we're probably not lucky enough to be able to code in whatever language it is that writing the framework in in the first place so yeah we get to learn a whole another tiny little programming language but basically just a way for us to deal with big chunks of HTML in a bunch of separate files and hopefully produce an HTML interface so let's look at django support for templates I'm gonna make a directory in my application I just happen to know that if you make a directory called templates in your application and you put templates there Django will magically be able to find it I could be more explicit I could go edit my settings and tell it hey my templates are stored over here but for the moment I'm taking advantage of this built in behavior so I made a directory called templates and a subdirectory called story if you know about Django you know why I did this if you don't maybe we'll get to in the QA session explaining why I repeated myself but I'm gonna make a template and call it based HTML so let's make a really minimal based on HTML template it's almost all just plain old HTML and it's like the simplest possible I guess this is an html5 page because it doesn't have a doctype simplest possible page I could make it should all look really familiar if you've ever looked at HTML before except for the middle bit that has brackets and percents and says block content and in block so Gengo comes with a templating language the templating language is what makes our temple it's not just static content but dynamic something's going to happen there in the block it provides a few fundamental concepts tags filters and pretty much just output the ability to say print this variable block is a Django template tag so what does block do for me I got to do one more thing I want to make a second template same directory it's in my story templates story directory and it's called homes out HTML and this is what home dot HTML looks like the first line says extends story base HTML it's got a block again and then the thing in the middle where there's two braces is basically the print statement so I'm just gonna print out some variable hello I don't know where that comes from yet it's kind of cool is the extends block is how Django does template inheritance which is the idea that every little template I make doesn't need to have the whole site design in it I'll keep that all in the base template the base template won't change very much and this is the template specific to a specific page in my application it extends the base template and the way Django's extension works is you have name blocks if the child template has the same name block as exists and the parent template the stuff on the child template shows up in the parent template so I have a block content here I had a block content in my base hopefully whatever hollow is is gonna end up in my base everybody still with me am i going at a good speed of them too complicated yet okay and Hello is going to output a variable that needs to be passed by the view so gee that means I get to go back and fix my view in this case I'm gonna import from Jenga dot shortcuts a function called render to response so this is one of those Django things the tutorial will walk you through ways to get lots of things accomplished and Jenko nots will frequently get frustrated with the long way to get things done and write a cool quick and short way to get stuff done and stuff it in the shortcuts module so you're gonna want to know about everything that's in the shortcuts module eventually render to response basically says well I know that you want to make an HTTP response and I know that you want to do it with a template library so if you give me a dictionary of variable names and values and a template I'd be in charge of putting those two things together making an HTTP response out of the resulting string and returning that back out of the view so here I am with my render to response I'm telling it hello is a variable it's just a string its contents our hello world if you've done a little bit of Python you'll notice I'm just making a little dictionary in line here and that's gonna render my home template and if everything worked out well I'm back to my web app so welcome to story time hello world yeah we got real HTML now it's so it's actually a web app so you're gonna have to learn a bunch about templates tags and filters and don't worry because they're really easy it's just that there's a bunch of them I've got links to the docs here to the templates page and also the reference to the built-in tags and filters there's tags and filters to do everything from logical operations like looping and if inside your HTML to doing string formatting things like saying Facebook style dates you know you give it a date time it says oh about three days ago you know lots of stuff for doing content manipulation none of it is particularly complicated or exotic but it turns out writing django web apps a lot of the programming that you're gonna do is in the template language in the templates so one more concept here fundamental concept number four is models we have a web app it says hello inside of a bunch of HTML generated by Python code but there isn't any like dynamic data right we're not talking to the database yet so that's what my models are for this is supposed to be a database backed web app and we're gonna need to create and read an update and delete all that good cred stuff data from a relational database and again you can kind of say so I don't know what relational database I should use I don't know SQL that well I don't even know what SQL means that's okay hopefully we're gonna be able to work with just Python code and until we really have to Django is going to obscure some of the complicated details from us but don't worry when you really need to get down to the rescue L you can totally that with Jango basically all you need to know is that models are database tables represented in Python code as Python classes so models are your handle to create the table in your database automatically to generate the SQL that you need to update the table in your database so query it to get data out put new data in update or delete stuff that's already there and you might sometimes hear the term thrown out warm it's an object relational mapper that's basically the category that Django's a model implementation falls into and pretty much you just need to know a model that we'll show you in a minute is a database table an instance of a model and make little objects from classes an instance of a model basically corresponds to a database row so here's a model it's really simple this is in my models dot py the models that py was generated automatically for me it didn't have any code in it just a helpful comment put your models here so I actually I think it had the import statement in it but I made a class called line line inherits from models model and line has one class level attribute called text which is an instance of a models dot char field so this is how a lot of stuff in Django works actually you write this declarative class that has class level attributes and there's some kind of relationship going on here my class is a model and it's got individual attributes that our model subclasses somehow or other they're related basically all the all the fields all the field types correspond to database columns so I'm making a text field that can store up to 255 characters here how could I use it it's worth noting that there's database stuff going on behind the scenes I didn't specify like a primary key on my table and if you know relational databases you know I probably should have it's okay you don't have to do that Django will notice that I didn't and automatically give me an an ID auto number primary key sort of field behind the scenes how could I create the tables you probably used to it by this time there's a management command for that so I run Python managed uh py sync dB it runs through creating tables so it's generating the appropriate SQL from my back-end how do you create tables on SQLite I don't know off the top of my head actually I know like MySQL and Postgres better I don't know if I could type out an SQL create table statement without error in SQLite but that's okay cuz Django is gonna do that for me and you might notice the very bottom one down there at the bottom creating a bunch of tables stuff that comes built in with Django but the bottom one says creating tables story underscore line that's the table that corresponds to the model that I just made so now that I've got my database created I could try just using the models API like in the interactive Python shell I'll hold off the question about the interactive Python shell for a moment you probably used it right you can just type Python normally and you get a little prompt it's got three errors you can type Python code and hit enter execute so right away you really ought to be using ipython we'll talk about that I can't just say Python in the context of Django if I want to talk to my models they need to know like which project they're in so they know which database to talk to so there's a management command to launch the Python prompt Python manage py shell starts up a Python shell with the Django environment kind of configured for me and then I can say from story top models import line that's the class I made just kind of looks like a normal Python and things like line text equals that looks like I'm instantiating a class right you call a class in Python to make an instance of it I'm getting back line which is a Python object when I called line dot save that Python object knows what database table its attributes should be stored in and how to get them there it's generating the SQL update statement for me so that's all the Python code it takes to create a new row of data in my database table and I could also like run a query I could say lined out objects dot all and that's behind the scenes creating a select star from whatever my table name is getting all the data back and I get back a thing that kind of looks like a list it's a query set it's a really cool object if you get a little past beginning Django you'll spend a lot of time playing with query sets so let's update our view again and see if we've got through a database backed web application yet the only additional thing I need to do is from models import line so get the model that I made and my view now is gonna return a dictionary again it's got a key called lines and the value is lined out objects that also that's gonna be all the lines I've got in the database headed out to the template which also had to get updated I think I mentioned you're gonna have to do some programming in the template I still have the block content thing I've got a tag for an unordered list I think I left off the closing unordered list tag that's really horrible I've got some Django template programming in the middle like four line in lines it's pretty much a Python for loop stuffed in my HTML yeah you got to go look at the docs for the for the template tags for is a built-in template tag and here's another template tag it's called cycle anybody want to guess what cycle does chute indefinitely it's gonna give me one of the other back does anybody know about the Python built-in that does that so you should definitely check out the itertools module in Python there's lots of cool things around iteration and there's itertools cycle that does the same thing you give it a list and it gives you items from the list and when it reaches the end it goes back to the beginning so it's an infinitely long list that you can consume and like repeat some pieces of data okay and then I think we said before a couple of braces that's more or less the way you say print this thing and this case this thing is in a string it's a instance of my line class and instances in my line class have a text attribute so if everything worked out well yeah I have a an actual real webapplications pulling some data from the database showing it on the page in some HTML okay URLs views templates and models see the docs as usual how to define your models there's a lot of complicated issues there that we're totally gonna punt on tonight and how to make queries you can make cool and complicated queries with a Django arm and again we're totally punt on that unless you have questions in the Q&A period let me show you one more thing in the little app that I'm making there's an admin app that comes with Django it's sort of a selling point for Django just for free more or less I can uncomment a couple lines of my URLs a couple lines in the settings and add an admin dot py file to my application that looks like this pretty much just one line of configuration I'm telling the admin app hey I've got this class line you really ought to I don't know do something with it and for free you get a a crud interface to your data you can go edit I can go edit lines add new lines and if I add new lines then the lines would show up on the page and I started doing this because my third grade daughter keeps on bringing me stories that she writes for their classmates everybody writes one line they passed the paper down right and you know there once was a girl who had a blue hat suddenly a dragon jumped out you can ice tell like when she's sitting next to a boy by her stories okay so you wrote your first web app you're on your way to Facebook or Pinterest right I know so you need ever so much more than just that just like the fundamental concepts and Django actually comes with a ton more so there's a ton of shortcuts to use in views there's forms we haven't talked about that how we can accept data and validate it from the user those model forms to automatically make forms based on our models there's managers and complicated queries there's a caching framework built in there's logging there's like a bunch of stuff that I'm not even gonna say everything just a ton of stuff that you have to know about in Django management commands geo Django there's a whole section for doing GIS stuff that I actually don't know enough about and it's weird but all that and it's still not enough so Django was this huge framework there's a ton of batteries included if you went and downloaded the docs as a PDF it's like up to 1,200 pages now fortunate like 400 odd is geo Django which you can mostly ignore but there's a lot you have to know about and it turns out it's not enough for writing modern web applications so kind of a fundamental thing you do after you take the tutorial as you say I need some more pieces what pieces do I need and it turns out other people have written the pieces that you need third-party applications are a fundamental piece of Django the framework is made to make it easy to compose your project out of lots of apps so you're gonna use lots of third-party apps everybody does it they'll supply missing pieces or maybe even just have like pre-built functionality that's exactly the thing that you need for your project I'm just gonna run you through a quick list without too much explanation of my like top 10 apps and I'm not kidding when I say I could totally do a top 20 Django projects frequently you start and then you install a bunch of favorite apps cuz you know you're gonna need them and I should just mention tools if you don't know like how to use virtual ends and pip to install stuff this is kind of fundamental Python knowledge so you should learn about that virtual embassy in to Python 3 3 but in earlier versions of Python you're stuck kind of figuring it out on your own and when you if we get to talk about deployment you should be using fabric real easy and also for your interactive console just use ipython already that's a different talk but you should you should check it out so my top 10 apps so this is the stuff you probably will need bits and pieces of this for your project database migrations and this is actually coming soon to django contribute godwyn just had a Kickstarter fundraiser sitting in like five thousand dollars to work on it for a couple of months and move it into the Django project proper and raise $20,000 what database do for you is you can go change the Python code for your models and it'll automatically update your database to match your Python code and you don't actually need this feature if you promise you'll never ever change your models in your project djenka debug toolbar got to have this it pretty much answers the question like okay what is going on in this page what view what templates what SQL query is what variables django doesn't help me very much if i start up somebody else's complicated project and see the front page i just have no idea how I got there so the debug tool board gives me a little HTML interface over on the side that tells me actually all those pieces of information how much time it took to build the page how many SQL queries got fired off what templates what variables the templates could see if you haven't used a debug toolbar kick yourself once and then go install it it's totally indispensable I'm lost and confused without it Jenko extras is a favor favorite developer goodies app that I frequently install it's got management commands that make management commands that's not a joke it's useful you can graph all your models use show Plus or run server plus to give you cooler shells and a cooler development server crispy forms and floppy forms basically gives you html5 form components like client-side validation for free bootstrap compatible output it's basically like beautiful gorgeous forms with no effort on your part and yes I cheated that's two apps in one bullet point but you need both of them haystack is a favorite of mine it's an API to search engines and we're talking search engines that you install on your server that serves your data and lets you do things like offer a search box for your data or if you liked this maybe you'd like this other stuff or you searched for so here's the page with the thing you search for highlighted that's really cool functionality haystack makes it easy to do that kind of thing tasty pie makes it easy to make a restful api for Django models a little bit of configuration and you get a big tree of JSON data some pre-built views that will let you even edit that data automatically if you like and if you're used to writing JavaScript in the client you're gonna totally need tasty pie or maybe you're gonna write an Android app or an iPhone app for your website it's gonna need to get data somehow or you just want to give other people an API for your site let them write a cron job that fetches data tasty pie makes that sort of thing really trivial I did connect to the server but or to the wireless well if you go look at my talk when I post the slides this is linking to YouTube I've got a video for celery which is huge I can't explain it you'll know when you want it and there's a five minute video that I just totally couldn't cram in here to go take a look at celery some easier applications like stuff that you'll want just right away easy thumbnails you got to deal with images easy thumbnails lets you resize stuff in template tags so you can say hey they uploaded this gigantic image resize it to 200 pixels by 200 pixels and keep the resized version around January version give yourself an undo unlimited undo on your models people make an edit you don't like it you can go back to the previous version everybody uses revision control software for your code right that's really useful now you can have that for your data too in your Django project and you might check out Django Grappelli which is my favorite like prettier admin skin and it's not just pretty it lets you make a custom dashboard and arrange things the way you like it and gives you things like you can drag and drop the order of records in the admin and it will update the the database or autocomplete lookups you start typing and it figured out what it is that you're looking for lots of cool handy stuff for the admin and so I'm flying past some apps that I use just to kind of give you the idea django has tons of high quality apps and some of them are totally just to provide you with pre-built functionality you need to register users great there's an app for that make appointments create menus all on and on and on there's an app for everything and that's kind of one of the fundamental like why Django so the Zen of Django is you have an idea that's not it's not your fundamental idea it's not your whole application but it's a little piece of it great make an app for that and by the way make an app and share it with me make it redistributable I want to use your app but if you do that you should make it you should make it pythonic and you should make it whatever the heck you're supposed to use to say it looks like Django I don't know what the I don't know what the right word is exactly and that's sometimes like a tiny bit complicated so Django isn't mad but if you're not an experienced Python dev it can look a little magical it does use some advanced Python features to try and give you like a nice clean easy to use API I want to show you one but I'm not gonna explain and show you another one and walk through and see what your level of interest is in understanding an advanced language feature that might give you that might give you great power so the first one is declarative classes if you've done Django stuff you kind of recognize this pattern models it's a class it's got attributes that are instances of another class forms it's a class it's got attributes that are instances of another the class model forms same deal third-party apps like tasty pie same kind of looking API you make a class and I can just keep on going like haystack indexes are built that way Django sitemaps the RSS framework everything kind of looks like that and it's really weird because you're building declarative classes whose class attributes are instances of a related type so you have models and their model fields forms with form fields but the class that you get back the object you get back by instantiating the class doesn't actually look like the class that you defined at all if you've done enough Python to know the difference between object level variables and class level variables yeah those those bits of code should weird you out a little bit made lots of class level variables instead of object level variables what's going on Python has this feature called meta classes you can just totally change what it means to make an instance of a class when you instantiate a class instead of giving you an instance of my class I can give you an instance of some other class just use your class for configuration if I want to and that that's deep dark magic right it isn't it's just a powerful language feature it is deeper than we can go in the you know 15 minutes that we have left but it is within your grasp like you can understand meta classes you could provide an application that uses like that nice style of API let me show you something else that's a little easier a little easier to grasp but it's kind of cool to decorators so getting rid of some complexity with decorators if you've done a little bit of Django like just a touch you've probably seen there's a decorate called logged in or sorry login required so you can use the login required decorator just by putting I added one extra line of code to my views well - I imported the decorator and then I said at login required just above my home function which is a view so it's pretty cool what it actually does is if you hit my page and you're not logged in it'll send you off to the login screen and then bring you back and if you are logged in it just lets you see the view that you're on transparently really minimal effort on my part right I just put at log and required I don't really have to know how it works decorators are kind of cool let's write a decorator cause it does something cool for us so I'm gonna move fast here if if you haven't done like much functional programming with Python if you haven't looked at decorators before we'll see how we do but I do have a blog post that's you know twelve easy steps to decorators so it's really long it's about as long as this talk and if you haven't done decorators before you could go read that talk and a send me a question send me a comment if something is unclear to you but simply a decorator is just a function that takes a function and returns a function that'll maybe be in place of the original thing so here's the simplest decorator that I can think to write I have a dictionary called library I'll have a function called register a function register takes a parameter that is called F and F's name attribute becomes a key in the dictionary and F becomes the value and I return F anybody unclear about what the function register does two lines are really simple code right puts the name in a dictionary give us back whatever it was that got passed to it okay that is a decorator it turns out so I can say at register just before a function and my function doesn't do anything but that register syntax is basically me telling Python hey my func wrap it in this other thing and substitute whatever this other thing returns in the place of my funk and register returns the original function so my func is totally unmolested unmodified but when python runs this code that library variable is going to end up with a key and a value it'll be a function and the actual function itself if the decorator and it's actually useful because hey that's just what Jango does if you want to make your own custom template tags or filters you can't call arbitrary Python functions and your templates because that might be insecure it has to keep a list somehow and it does it by using a decorator now magic just Python so let's make a useful decorator that doesn't come with uh doesn't come with Django it turns out our views need to return a thing called a request context and request context is pretty much there's a lot of variables that you want to see in your template like who's currently logged in for instance we can just get those for free if we make a request context and I can do that manually in my view and it really kind of sucks I have to add this third line to my render to response shortcut that says yeah I have a template I have my variables and then go make another dictionary full of variables called a request context and post a file the request to do that it's an ugly line of code don't like that at all but we could use the render shortcut to automatically build a request context for us you give the render shortcut the request and the template and your dictionary and it does that request context thing for us so that's better well let's go one step further and here's the code sample that might be that might make you think so let's let's take a minute on this code sample we made a class called render inherits from object it has an init function what's the what's the init function on a class more or less the constructor it's not really the constructor but yeah we've mostly donut right constructors in Python which is cool which left-right this initialization function so this is what's gonna be called automatically when I make an instance in my class okay and I'm expecting it to be passed a template I'm just gonna store the template on the object that we have that first mandatory parameter self it's the pointer to whatever the current instance of the object is and then I have an underscore underscore call function how about that any guesses about the underscore call function what that has for me go for it yeah so basically what I have to do is is a decorator has to be a callable which is a function you can call functions right turns out you can call objects - if you provide an underscore underscore call method so you might know about magic methods dunder score methods Python does its operator overloading thing by saying hey if you made a special function that's underscore underscore ad then you'd be able to use Plus on your objects if you made a special function called underscore underscore call you'd be able to use two parentheses the call operator on the end so I just made a class that will make callable objects okay so when you call this object you're gonna pass it a function and it's gonna make a function called wrapper and give you back wrapper instead of the function it was passed in okay so I am making a configurable decorator here and whatever function gets decorated by this decorator is going to be replaced by wrapper so what does wrapper do wrapper calls the original function that's the self dot function part it passes it a request and whatever else had got star args stars is kind of pythons way of saying hey if there were more positional parameters coming into this function then catch them in a variable that'll be a two pole and star args when I call the function is pythons way of saying you know you've got a list of stuff passed this as positional parameters of some other function so it's a it's a flexible function definition and calling piece of syntax and you should totally have star and star start down cold and and then it's gonna do hey that's the Django part the render it has a request object it has a template object and has a context it got the context by calling the thing it wrapped around so how would we use this my view looks like this now I have that at login required decorator like I did before you can have as many decorators as you want I have the decorator we just wrote it's called at render I passed the template name and now my view just has to return just the dictionary the template name isn't inside of my function the request doesn't have to be manually passed because my decorator kind intercepts that and gets access to it um quick show of hands if you felt like not that you could write this but that you understand all the code that you just saw the last two slides will see your hand okay so that's totally cool decorators are somewhere between intermediate and advanced Python but let me just encourage you this isn't magic this isn't rocket science it's not just for like special elite people that are going to like be language lawyers or something if you take a piece at a time decorators make sense they use the built-in features language Python supports closures supports the star and the star star operator can define functions inside of functions if you rule about scope and lookup not too bad there's just a lot of moving pieces kind of the point of this is the decorator is cool it made my code a little simpler if I had a bunch of views my code would be a lot simpler but I get students that ask me all the time you know so how do I get better at Django and I have three responses for you and the last one is maybe why you're here the first response is just practice you know write some Django apps the best thing is just to plunge in and do it the second thing is you got to read the docs cuz the the documentation for Django is awesome there's a lot of them you are gonna have to read every link on the front page sorry about that start with the tutorial make things easy but my answer number three is hey you're here get better at Python or in Python well Django doesn't have any magic it just has Python and a few quote unquote advanced language features to make your life easier doesn't have to make your life easier you can you know write a django app and make my life easier as well if you understand Python well come see us at Maracana comm check out our tech TV YouTube channel there's lots of free content about Django and Python and JavaScript and lots of other cool stuff and that's it for my talk [Applause] [Music]
Info
Channel: InfoQ
Views: 464,191
Rating: 4.8870497 out of 5
Keywords: Django Web Framework (Software), Python (Software), Simeon Franklin, Marakana, Web Development
Id: zTNA0MtZwso
Channel Id: undefined
Length: 53min 24sec (3204 seconds)
Published: Thu Jul 11 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.