Creating a Home Page with Django: A Step-by-Step Guide
That's it, we say go into the views file and run the index function. So under views, this is the index function, and it will run that. We're naming it index, so then later, if we want to from our templates, our HTML, if we want to refer to this specific URL path, we can just call it by index and it will reference it.
Okay, the next step is to point the route URL configuration at the polls/url module. So, URL conf, and we gotta point it to this. All right, in mysite/urls.py add an import for django.urls.include and insert an include in the urlpatterns list. So you have this. We're gonna go in our mysite/urls right here. In here we're gonna say if somebody goes to the path polls, then run the polls URLs.
Okay, so from django.contrib import admin from django.urls import, from django.urls import include, path. And that's because we're gonna do the include thing right now, just like that, and then hit Save. So if somebody types in john.com/polls, now we'll say hey, try to match this pattern by going to the polls.urls file.
Well, where's that? That's in the polls app, and it's this file right here. So then it will go to this file, and then it will match this first guy and it will say okay, I'm gonna run the home function. So anytime somebody goes to anything polls, it will refer it to that file, that URLs file.
All right, this is what they're basically saying here. The include function allows referencing other URL confs. Whenever Django encounters include, it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URL conf for further processing. The idea behind include is to make it easy to plug and play URLs, since polls are in their own URL conf, they can be placed under or any path, and the app will still work.
Okay, you have now wired this up, so now it says you should always include, you should always use includewhen you include other URL patterns. And now it says you have now wired an index view, let's verify it's working, run the following command. Okay, so now we're gonna run this thing, and we'll go to our localhost, or this http port over here. And hit run.
And now we are getting an error, oh yes, basically, you have to do polls. Okay, of course. Because it's not a home page that we've added to, because I just saw this and I was like, oh, homepage. But it's because we got go to the polls path. So everything after, so it's like when you put this online, when you put this app online, it will essentially be like yourapp.com/polls is where you'll have to go to, and then it will know what to do, okay, so it's saying you are at the polls index.
And that's exactly what we see now, cool. Go to this in your browser, and you should see the text which you define in index. The path function is passed four arguments, two required, route and view, and two optional.
At this point, it's worth reviewing what these arguments are for. All right, so we're not going to go into too much detail, it's gonna be like still casual and we're gonna keep moving forward.
Awesome, I hope you were excited watching it up until this point. Now, in the next video, we're gonna go to part two.
Before I let you go, I do wanna let you know that I have a course called "A Profitable Programmer" coming up, where if you're more serious about, you know, becoming a web developer, learning Django more in depth, and especially learning how to get clients with Django and Python, and to start working as a developer, then definitely go to this page.
We'll put this link right over here, and basically I want you to sign up and put your email for our VIP wait list, so then you're the first one to know when this course opens up, and also I'll send you my resources that helped me become a developer in less than three months, and I'll give you that as a gift for free, okay, for joining this wait list.
"WEBVTTKind: captionsLanguage: en- What is up, how's it going, this is Qazifrom cleverprogrammer.com.What I wanted to coverin this series is Django.And what I wanted to coverwas the most commonlyreferenced Django documentation.I personally couldn'treally find any videosof people covering it, soI just wanted to do that,because, you know, I see,everybody who starts learningDjango, this is the firstplace you're gonna go to,like the docs, the Djangoofficial documentationthat shows you how to dotheir getting started guide.And so I just wanna kindacover that in this series.This first video, we're gonna do part one,and then every video afterthat we're gonna just coverone part, so like thesecond video will coverpart two of the documentation.It's gonna be done in amore conversational style,and I hope you enjoy it,so let's get started.So basically Django at a glance.The beautiful thing aboutDjango, what they're saying hereis that it lets you doweb development tasksin a really fast way, soit's pretty intelligent.Like for example, one of theawesome things about Djangocompared to any otherframework, even like node.js,right, which is very popular,and it's a great, great,great framework for JavaScript,but what makes Djangoreally cool is that itcomes with a built-inand very robust admin interface.So, if you're buildingan app for your clientwhere, let's say you wantto build a blogging appfor somebody, or eCommerceapp for somebody in Python,if you built it usingDjango, it gives theman admin interface, sothey can just go in thereand do stuff from there,or you can manage the appfor them from the admin interface.And, imagine this, you had tospend zero development timeon doing that, which meansthat they're gonna thinkyou're a fricking magician,and they're gonna wantto hire and be like, wow,how did this guy do this.So, the admin thing is pretty cool.So, and just right now Ijust wanna kind of coverthe overview, and then we're gonna jump into actually the partsof the tutorial, okay,and you're just gonna follow me along.All right, so, I'm gonna coverthis, kind of touch on this.So if you have some experience with it,it will make a little bit of sense.So designing your models, so in Djangoyou can kind of design yourdatabase and models like this.You don't need to type in raw SQL queries,or mess with too many ORMs,it's just simply classes,so it's literally likePython and object orientedprogramming, and boom,you have stuff populatingyour database, which is pretty cool.It also has a built-in kind of API,so it says, you know, assoon as your models are done,the API's created on the fly,no code generation necessary, okay.So here you can see thatif you create a model,let's say that you'recreating an app, right,and it has reporters, andyour app has articles,you know, well, what youcan just do is just be likeReporter.objects.all and it will tell youhow many reporters are there.For example, if you madea game app for let's sayStreetfighter, and youdid Fighter.objects.all,it might say empty set, which meansyou didn't put in any fighters yet, right.But then let's say you createa fighter or a reporterwith the name John Smith, and you save it,then, when you checkobjects.all, all of a suddenit'll say hey, reporter JohnSmith actually does exist.So, that's pretty cool,and a really nice wayto interface with it.And then also you can search for thingsin a really easy way too.So you can search inyour database with an ID,but you know, a lot of timesa more human way to searchinstead of an ID is, like, searching withwhat does the name startwith, or if the namecontains the word mith, whichSmith actually contains,and it'll match it.So then what you can do onyour front end later is,right now, you're not gonnahave your client interfacewith your app from thecode command line, right.What you can do later isthen give them a front end,an interface, so they can actually type itin the search bar and look up John Smith,or type in mith, and it'llstill find John Smith.Kind of like when youguys go to Shopify stores,or YouTube, and type in a video's name,and even if you're off,it'll still find it,it's using this containedsearch mechanism,which Django comes built-in with.Another thing I wanna touch on is,yeah, if you have yourmodel, you can registerthem in the admin interfacewith just a simpleline that says admin.site.register,and then that model will,so let's say you createdthe Article model,you can now register itin the admin interface,so then you can go an point and clickin the admin interface, and then deleteor create new articles or what not.For example, when youhave a WordPress blog,you know how you have anadmin interface there,and you can create a newblog post, or delete a postor edit, you have full CRUD functionality.Well that's what it mimicsby you just doing this.And that's you creating code from scratch,that's kind of powerful.And then, obviously, let'syou design your URLs,so how do you want your URLs to be?So for example, you canhave it like, you know,myapp.com/articles/the year,followed by whatever, right.So you can create your ownURL parameters and whatever.So this is pretty standard,but Django let you do itin a really clean way,especially with Django 2.0,their latest release.All right, so, writing yourviews is also pretty easy.You can have it just likereturn an HTTP responseor HTML file you made.So for example, here you can see we renderand return this archive.html file.So if you create an HTMLfile in your templates,then it's gonna be there.Again, if you're watchingthis, and you're like,I'm a complete beginner,and I have no ideawhat the heck you'retalking about, don't worry.If this part is just not making any sense,skip a little bit ahead to the partwhere we jump into the tutorial.This is just for peoplewho are maybe comingfrom other frameworks,and they wanna grasphow Python and Django is working.So, you do need someexperience to understandwhat I'm talking about here.And then yeah, templates are usingit's using Django templates,which is kinda like Jinja.I'll go into this later.So, at this point, let's just get started.All right, so for yourinstallation all you really needto do is make sure youhave Python installed,so for myself I got Anaconda installed,which is what I would recommend for you.So if you do anaconda download online,kind of install that,and that's pretty muchall you need to go on.And then, obviously,install Django as well,which I'll show you in one second, okay.All right, and then you can go aheadand create a project.So we're gonna just getstarted from scratchand follow along with thistutorial, so let's get started.Okay, so I'm gonna openup my command line here.So I'm just gonna open up my terminal.If you're watching this,you can open up your,you know, CMD on Windows,or, what I recommend installingis CMDER on your Windows.Basically just see if youhave anaconda installed.And if you do, and if you type in conda,this thing should come up, okay.If you don't have anacondainstalled, that's okay,you can still follow mealong, but what I'm doinghere is kind of like for best practice.So, if you want to do itlike the best practice way,then I recommend that youget conda installed here.Let me just make thisa little bit smaller.All right, so basicallywhat I wanna do here isfirst, check my, so, whatI'm gonna do is installmy environment with conda,okay, so I'm gonna do,and again, installinganaconda, and like making youunderstand everythingabout a virtual environmentis outside the scope ofthis specific tutorial.You can look up stuff likehow to install anacondaon Windows, or how toinstall anaconda on a Mac.But I'm just gonna go aheadand do conda, or first,I'm gonna create thisproject, so let's just see.I'm gonna go to my GitHub.All right, what I'vealso done is I have goneinto preferences in my Atom, and I havewent in under install, and I've installedterminal, platformio-ide-terminal,and I've installed it.So then the beauty of that isthat when I'm coding, right,if I'm coding I can just popopen my terminal right in here,and I don't have to leave my Atom.So, I will do django-admin startprojectmysite like that, and then go into mysite.Okay, and then I will comeover here, and I will open,I'll go to GitHub, andthen I'll go mysite,and then just click that, okay.That's about it.This is just so if youguys are following along,like, I don't want you to get confused.I'm gonna open up my Chrome.So they're saying that this is pretty muchwhat it should looklike, and for us it doeslook like that, right, we have mysiteand it has all these files inside of it.And you can see mysite,and it has all these filesinside of that, okay.And then they say, hey, just go aheadand run python manage.py runserver,so let's go ahead and give that a try.So I'm gonna open up my terminal,and how I do that, how Iopen up that little promptis by doing command + shift + P.For you on Windows, thatmight be a differentcommand, like, maybe Control + shift + P.But yeah, for me that opens it up,and then I just click terminal,pops open my terminal.I'm gonna do conda create --namemysite python=3.6And I will activate this environment.And now, I will install Django.Okay, so if I do pip freezeit should show me thatDjango and a bunch ofother stuff is installed.Django right here, so we're good.All right, I'm just make the fonts biggerso you guys can see it a lot easier.Okay, so now we're gonna try to run this.Python.manage.py runserver.And we will go to this URL on our Chrome,and see if it shows us something.Okay cool, so it saysinstall worked successfully,congratulations, and, believe it or not,this is actually pretty excitingbecause this is the firsthint that your app is actually running.Now to this we're gonna adda lot more features to itand make it really awesome.But right now it's being actually servedover your localhost and it's running.And once we get it to apoint where it's doing a lotof cool stuff, we'll developit locally and then later on,what you can even dois then put it online,so then anybody in the worldcan use your Django app.Let's go back, and let's takea look at what the tutorialis telling us to do at this point.So it says that you shouldsee this stuff, and we do.And then it says ignore the warningabout unapplied databasemigrations for now,we'll deal with thedatabase shortly, cool.And it says we have starteda Django development server,which is a lightweight webserver written purely in Python.We've included this in Djangoso you can develop thingsrapidly without havingto deal with configuringa production server such as Apacheuntil you're ready for production, cool.All right, and they saydon't use the serverin anything resembling aproduction environment,it's intended fordeveloping, cool, no problem.All right, and now theywant us to get startedon creating the polls, the polls app.Now that your environment- a project - is set up,you're set to start doing work.Each application you writein Django consists of a pure,of a Python package thatfollows certain convention.Django comes with a utilitythat automatically generatesthe basic directory structure of an app,so you can focus on writing coderather than creating directories, cool.All right, projects versusapps, so what's the differencebetween a project and an app?Now, the cool thing with Django is thateverything is considered an app.So let's say that you create a websitethat has a blog, that hasa eCommerce capability.Now, the blog is considered,so let's say you created thiswebsite with Django, right,the blog would be considered a Django app,and your eCommerce store would actuallybe considered a different Django app.So there would be two different appsthat your web application is comprised of.That's how Django handles the logic.So, basically it's one projectthat has multiple apps inside of it.That's pretty much whatthey're saying here.Okay, so an app is a webapplication that does something,okay, so web blog system, adatabase of public records,or a simple poll app.A project is a collectionof configuration appsfor a particular website.A project can contain multiple apps,an app can be in multiple projects.So, you can have one app thatyou build for one project,and you can actually haveit in different projectsthat you're doing, which is really cool.It's like plug and chug.Your apps can live anywhereon your python path.In this tutorial, we'llcreate our poll appright next to your manage.py file,so that it can be importedas its own top-level module,rather than a sub module of mysite.To create your app, make sureyou're in the same directoryas manage.py and type this command.Okay, so now this command,manage.py startapp pollswe're gonna do that, okay.So, we're gonna break ourserver with control + C,okay, so I did that.I'm gonna hit ls, and it lookslike I'm at the same levelas my manage.py file.If I hit pwd, pwd, it'llshow me where I'm at.And now, I'm gonna dopython manage.py startappand the app is called polls I believe,just let's double check.Okay, so now our polls app is created,and let's just take alook inside of polls.Okay, so inside of polls you can seethat we have a bunch of, oh actually,let's look right overhere, it's easier that way.So polls comes withmigrations, _init_.py, admin,apps, models, tests, views,there's a lot of thingsthat polls comes up with automatically,which is really nice.But a lot of this stuff is, you know,just kind of empty.The main things that you'regonna be working withis models and views,okay, that's the thingyou're gonna be working with all the time.When you're developing apps for yourselflater, you're also goingto be playing aroundquite, you're gonna beadding stuff to tests,to make sure you can test yourapp as you're building it.And then migrations isgonna be important becauseit's gonna kind of let youtime travel in your database,so when we keep makingchanges to your database,with migrations, you can rollforward to a certain time.But let's say things get really messed up,you can roll back to aprevious point in time.All right, so the thisdirectory structure will housethe poll application.So this is the directorystructure that we actually saw.And now, they want usto write our first view.A view is what lets yougo to a specific URLand then it returns some kind of response.So for example, so Djangoworks off of somethingcalled MVT, which is calledmodel view templates.Your normal apps, youknow, node.js, or whatever,those frameworks work off ofMVC, model view controller.So, to give you an exampleof this in real life is,when you go to Google.com/, you know,when you go to Google.comand you type in cats, right,or let's say you go to Google.comand you type in whatever,the response that comes to you, right,that maps to the current URL you are at.So how does Google know toshow you the Google logoand the Google homepagewhen you go to Google.com?So, Google.com, when you type it in,it sees what your current URL path is,then it goes into the Google code base,and then it finds this HTML filethat says, if somebody goes to this paththat says Google.com, thenshow them this HTML pagethat has Google's image onit followed by a search bar.And it shows you that, okay,so it returns a response.You request something,and it returns a response.If you go to apple.com/watches, or watch,I don't know if that'sactually a real Apple URL,but let's just say you'retrying to get the Apple watch.So if you go to apple.com/watch,how would it return toyou all of their watches?So, what actually happensis, apple.com/watchwill match that path in their code baseand then it'll see ifthere is an HTML filethat corresponds to it,and it will show youthat HTML file, okay, as a response.And that's essentiallywhat we're gonna do,but we're gonna have avery basic version of it.So, we're gonna go in our polls/views.py.So I'm in my polls, and I'mgonna go in my views.py,so when they say it likethis, polls/views.pythat's what they mean.And then here I'm gonnasay from django.httpimport HttpResponse, right,and then I'm gonna go here,I'll say def index(request)to take in a request, andthen return HttpResponse.And I will say Hello World,You're at thelet's do it with double quotes becauseHello World, You're, what is it,at the polls index, right,and then the have a little comma here.This doesn't matter somuch, this is just a string,so it doesn't matter what you do.Make sure you alwayssave what you're doing,because otherwise itwon't take any affect.So make sure you do Control + Sor Command + S the whole time.So I just created this, but the thing isit's not gonna show up.So now, what I need to do is tell my appthat when somebody goes to the homepageyo, you gotta show thisexact, this thing right here.This is the simplestview possible in Django.To call the view, weneed to map it to a URL,and for this we need a URL conf,or a URL configuration.To create a URL confin the polls directory,create a file called urls.py.Your app directory shouldnow look like this.So now notice there's a urls.py here,which was not there before.So we're gonna go in ourpolls, right click here,and create a new file and call it urls.py.And now, in our urls.py wegotta add from django.urlsimport path, from django.urls import path,and then we're gonna do from import viewsand then we're gonna do a urlpatterns.So, what you wanna do is try not to indentbut use four spaces instead,okay, one, two, three, four,if it doesn't automaticallybring you to the right place.And I wanna do path, so ifsomebody goes to the empty paththen I want you to go into our views fileand use the index function,and we're gonna callgive it a name index.So what does this mean?If somebody goes to,let's say your websiteis called john.com, right.If somebody goes to john.comfollowed by nothing else,so not like john.com/article,/blog, none of that,it's just john.com, yourhomepage, what happens?Well then, we say go into the views fileand run the index function.So under views, thisis the index function,and it'll run that.We're naming it index, so then later,if we want to, fromour templates, our HTMLif we want to refer tothis specific URL path,we can just call it by indexand it'll reference it.Okay, the next step isto point the route URLconfiguration at the polls/url module.So, URL conf, and wegotta point it to this.So, all right, in mysite/urls.pyadd an import for django.urls.includeand insert an includein the urlpatterns list,so you have this.So, we're gonna go in ourmysite/urls right here.In here we're gonna the,this line, okay, becausewe're saying if somebodygoes to the path polls,then run the polls URLs.Okay, so from django.contrib import adminfrom django.urls import, from django.urlsimport include, path.And that's because we'regonna do the include thingright now, just likethat, and then hit Save.So if somebody types in john.com/polls,now we'll say hey, tryto match this patternby going to the polls.urls file.Well, where's that?That's in the polls app, andit's this file right here.So then it'll go to this file,and then it'll match thisfirst guy and it'll say okay,I'm gonna run the home function.So anytime somebodygoes to anything polls,it'll refer it to thatfile, that URLs file.All right, this is whatthey're basically saying here.The include function allowsreferencing other URL confs.Whenever Django encountersinclude, it chops offwhatever part of the URLmatched up to that pointand sends the remainingstring to the includedURL conf for further processing.The idea behind include is to make it easyto plug and play URLs,since polls are in their ownURL conf, they can beplaced under, or any path,and the app will still work.Okay, you have now wired, so now it saysyou should always include,you should always use includewhen you include other URL patterns.And now it says you havenow wired an index view,let's verify it's working,run the following command.Okay, so now we're gonna run this thing,and we'll go to our localhost,or this http port over here.And hit run.And now we are getting an error, oh yes,basically, you have to do/polls, okay, of course.Because it's not a homepagething that we've added to,because I just saw this andI was like, oh, homepage.But it's because we gottago to the polls path.So everything after, so it's like,when you put this online,when you put this app online,it will essentially belike yourapp.com/pollsis where you'll have togo to, and then it'll knowwhat to do, okay, so it'ssaying your at the polls index.And that's exactly what we see now, cool.Go to this in your browser,and you should see the textwhich you define in index.The path function ispassed four arguments,two required, route andview, and two optional.At this point it's worth reviewingwhat these arguments are for.All right, so we're not goingto go into too much detail,it's gonna be like still casualand we're gonna keep moving forward.All right, awesome, Ihope you were excitedwatching it up until this point.Now, in the next videowe're gonna go to part two.Before I let you go, Ido wanna let you knowthat I have a course calleda profitable programmercoming up, where ifyou're more serious about,you know, becoming a web developer,learning Django more in depth,and especially learning howto get clients with Djangoand Python, and to startworking as a developer,then definitely go to this page.We'll put this link rightover here, and basicallyI want you to sign up andput your email for our VIPwait list, so then you'rethe first one to knowwhen this course opensup, and also I'll send youmy resources that helpedme become a developerin less than three months,and I'll give you thatas a gift for free, okay,for joining this wait list.With that said, that'sit, and I'll see youin part two of this tutorial.For those of you guyswondering what the hellthose choice.set thing,it actually comes built inand you can actually change thatby passing in a relatedname keyword argumentwhen you're creatingthe question attribute,and you can give itwhatever name you want.\n"