Python Django Tutorial: Full-Featured Web App Part 2 - Applications and Routes
20:27

Python Django Tutorial: Full-Featured Web App Part 2 - Applications and Routes

Corey Schafer 31.08.2018 904 244 просмотров 22 680 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Django Tutorial, we will be creating a blog application within our Django project. We will also learn how to create URL patterns that are handled by our application views. Let's get started... The code for this series can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python #Django

Оглавление (12 сегментов)

<Untitled Chapter 1>

hey there how's it going everybody in

adding a blog application to our django site

this video we'll be adding a blog application to our Django site and also setting up some URL routes so that we can start directing people to pages that we'd like them to see so let's go ahead and get started so first let's create a blog app for our site now a lot of people might get confused at this part and think to yourself well didn't we already create an app so the thinking behind Django here is that you have your website project which we've already created and then within that website you can have multiple apps that are all their own thing so for example we can have a blog section of our website and that will be its own app and then we could have like a store section of our website and that will be its own app so a single project can contain multiple apps and we'll see later in the series that this is a good thing for separating out different parts of our project and another nice thing is that you can take a single app and add it to multiple projects so let's say that you really like the blog part of your application then you can simply drop that app into multiple websites so hopefully that makes sense and I think it'll make more sense once we see this in action so let's create our blog app within our project so currently I'm in our project in the same directory as our manage py file and we're going to use that to create a new app so we can just say Python whoops let me click on here so we can say Python manage py and then start app is the command to create a new app and now the name of our app and we want this name to be blog so I'll run that and once that's run let me clear the terminal here so that we can see the structure that we just created okay so now let me use that same tree command that I used in the last video to print

print out our project structure

out our project structure now that we've created that app and again you might not have this command installed but don't worry if you don't I just installed it so that we could see this layout a little bit larger so I will run a tree and now let me see if we can see this all in one screen here so yeah so we can barely fit all that in okay so we already went over the structure of the Django project in the first video so that was the manage py file and the

the django project directory

Django project directory here so nothing changed there but now we have this new blog directory with its own structure and that blog directory is what that start app command created now this is what can some people about getting started with Django because we really haven't done any coding yet and there are already so many different files that have been created from the start project and the start app commands so if anyone has watched my Flash series then this might be intimidating compared to my framework like that because we have so many more files that we're starting out with before we even start doing any coding but even though those commands created a lot of these files we're going to get so much more out of the box than what we got with a smaller frame work like flask so there's definitely a trade-off there so instead of going over all of these right now let's just go ahead and get a view created so that we can actually write some code and see some progress but don't worry we'll be exploring some of these other files that were created pretty soon so the first module that we're going to open up is this views dot

views dot pi module within the blog directory

PI module within the blog directory so now I'm going to open up my sublime text and open up that views dot PI file and again that views that PI file is within the blog app directory that we just created and we can see that it already has an import here at the top so it's already imported render for us and we'll use that in just one second but for now I'm also going to import HTTP response and that's from django HTTP so i will say from django dot HTTP import HTTP response and now i'm going to create a new function here and i'm going to call this function home and this function is going to handle the traffic from the home page of our blog and this function is going to take in a request argument we aren't going to be using the request variable just yet but we need to add it in order to just get our function to work and within this function we're simply going to return what we want the user to see when they're sent to this route so this is where the logic goes for how we want to handle certain routes so I'll create this function and that is called home and like I said this takes a request argument that we're not gonna use right now but it has to be there so for now we're simply going to return an HTTP response that says that we've landed on the blog home page so I will return an HTTP response and I will just make this an h1 tag so I'll say h1 log-home and then it close out that h1 tag okay so like I said this is the logic for how we want to handle when a user goes to our blog homepage but we haven't actually mapped our URL pattern to this view function just yet so to do this we're going to create a new bot

create a new bot module in our blog directory

module in our blog directory called urls dot pi and in that file is where we'll map the urls that we want to correspond to each view function so let's do that now so within our blog app directory I'm going to create a new file and I'm going to call this URLs dot pi now this URLs module is going to be very similar to the URLs module that we saw in our Django project so if I open up the project level URLs PI file then we can see that they have imported this path here and then they have a list of URL patterns that are using those paths and we're gonna do something very similar so I'm going to copy this import of the path from Django URLs and I'm gonna paste this into our blog URLs module and I'm also going to copy those URL patterns so I will copy that and paste that into our blog URL spy file as well now we're also going to be using this home view function here within our URLs so what we're going to do is import this view spy module within our URLs so I'll say from dot which is the current directory import views and I'll save that so now let's create a path for our

create a path for our blog homepage

blog homepage now right now this says admin and that is the view that gets run when we go to forward slash admin but if we want this to be the home page then we can just leave this as an empty path and now we want to specify the view that we want to handle the logic at that home page route and we want that to be our home view from our views module so we'll save use dot home and now I'm also going to put in a name for this path so I may say name is equal to blog dash home okay so we have an empty path and the views dot home is the function that we created in the views that just returns that HTTP response that we are on the blog page and you might be wondering why I put the name as blog - home instead of just home and that's because there will be times that we want to do a reverse look-up on this route and naming this something as generic as home could collide with other app routes so if I had a store app then maybe they have an app that has a home route also so I'd want to be clear with the actual naming of this path okay so now we have the URL path for our blog homepage mapped to our home function in the views file but this still wouldn't work quite yet because if you remember we have a URLs module in our main project directory also and that URLs module will tell our whole website which URLs should send us to our blog app now that might sound confusing but let's just pull this up so we can see this in action so now I'm open opening my projects URL spy file and like we've seen them before we already have one route here of this admin that gets mapped to these admin site URLs so we're gonna do the same thing but instead we're gonna tell Django which route should get mapped to our blog URLs so we're just going to need to import another function from Django URLs and that is going to be the include function so up here what from Django URLs we also want to import include and now we can

add to our list of url patterns

add to our list of URL patterns to specify which route should go to our blog URLs so I will add onto this and I will let me just copy this path here and paste this in so I'll say that if we go to blog then we should now reference our blog URLs and to do that we'll use that include function that we imported there and this is going to be a string blog dot URLs okay so now when we open our web page in the browser and go to word slash blog then it will map that to our blog URLs and then within our blog URLs we have that empty path maps on to our home view and we'll be sure to walk through this a couple of times just to be sure that you're getting all of this correctly now on one other side note here if you've watched any Django tutorials before then you might have seen people who use regular expressions to match their paths and that used to be how we would used to do this but this isn't required anymore in later versions of Django and regular expressions can be overly complicated especially when our routes are usually going to be pretty simple so I think it's best just to simply do our routes the way that we're doing them here okay so we've added a good bit of code so far so let's go ahead and make sure that this works and once we see that it does then we'll go back through all of this and explain exactly what's going on so let me open up my terminal and run our development server so I'll open up the terminal here and clear the screen and now remember to run that dev server it's Python managed py run server and if we run that then it says that the server is running we have to keep that running so now I'll open up Google Chrome and reload localhost on port 8000 so first of all if we go back to the root of our website then we can see that now we get a 404 page not found err so once we add some URL patterns then it should no longer display the default development site like it did before so now it's just going to try to match our specific routes so in this case we get a 404 and if we look at the debug output down here then we can see that within our terminal and that dev server that it also displays all of the routes that we try to access and the status code that we get so we got a four of worth there now back in the website if we look at our errors here I know this is a little small for you to see but this is showing us all of the URL patterns that it tried to match and it says against these URL patterns in this order so first there is admin and then there is blog and since it didn't match either of those then it returned a 404 page not found so now if we navigate to forge slash blog and run that then now we can see that we got the text of blog home and in chrome we can view the source of an HTML by right-clicking and then going to view page source and if I do that then we can see exactly what we return to this route here and we can see that this is blog home text wrapped in h1 tags so that worked so now let's walk through this one more time so that we can see exactly what order all of this goes through and let's also add another route to our blog just to get a feel for that so let me close down our source code here so when we navigated to forward slash blog in our website then it first looks in our projects URLs that PI module in the main project so if I open that up it looks in this file and it says ok someone navigated to Ford slash blog so do I have a pattern that matches that and we do it is the second one here so now that it matched that it says where do I want to send people who go to this route well I want to send them to blog dot URLs now whenever Jango encounters this include function it chops off whatever part of the URL has matched up to that point and only sends the remaining string to the included URLs module for further processing so in our example it's already processed this blog part of the URL so it's going to get rid of that and just send what's remaining to the blog URLs now there's nothing remaining after we chop off blog so it's just going to send an empty string to blog URLs so now let's open up blog URLs and see what it searches for here so now we're in blog URLs and now it's saying ok so now I just have an empty string because remember it's already processed the blog part so now do I have a pattern in here that matches an empty route and we do have a pattern that pattern will be handled by the function views dot home so then we can navigate to our views file and view that home function and now it comes into it simply says ok so now we just want to return an HTTP response with an h1 tag that says blog home so that is a walkthrough of the whole process so now let's add another route to our blog so that we can get a feel for this whole process here so now let's add an about page for the blog and we'll do this in the same order that we added the home page so first within our views we'll add a function that handles the logic for the about page and I will just call this about so I'll say def about remember we have to take in a request and then I'm just going to return an another HTTP response so I'll copy and paste that and instead of blog home let's call this blog about okay so now we have an about view so now within our blog URLs module we'll want to set up

set up the mapping for the path

the mapping for the path and that view function so if I open up our blog URLs then let's add another path to our URL

add another path to our url patterns

patterns here and I'm just going to copy the path that we already have for our home route and paste that in and I want this to be about and we'll in that with a trailing slash and we want the about view to handle this path so we'll say views dot about and we'll change the name of this to blog - about okay and at this point we should be done with that route so you might be wondering if we need to add anything to our project URLs module but we don't need to add anything to those URL patterns because that just simply tells our website that when someone goes to the blog route to send them to our blog URLs and then our blog URLs will handle this home and about route from there so let's open this up in our browser and make sure that worked so now if I go to our blog route then our blog homepage still works now if I go to blog ford slash about then we can see that now we have an about page that is working and now let's walk through this one more time now that we've added this about route so that we're sure that we understand this whole process so we've navigated to ford slash blog ford slash about so first it's

check the url patterns

going to check the URL patterns and our projects URLs module so i will open up and now our application is saying okay somebody has navigated to ford slash blog forward slash about do I have any patterns that match this and yes I have one had pattern that matches the /blog part so I'm going to send this to blog dot URLs for further processing and remember when it passes this to the blog URLs for further processing it's going to chop off the part that it's already matched and only send the remaining string so in this case it chops off the blog part of the URL and passes the about string that's left to the blog URLs so within blog URLs now it's saying ok now I'm looking for a route that matches about do I have anything that matches about and I do here so what View function handles this and it's this views dot about function so then if we go into views then we can see that we're returning an HTTP response with this h1 tag with the text blog about okay so hopefully that makes sense after we've walked through it a couple times now that might seem overly complicated to jump around that much but it's actually a good thing that the URL gets passed around like this because if we wanted to change the route to our blog application then we can simply change that in one place and it applies to all of those routes so for example let's say that we had a blog that was in development and we wanted to do some live testing on our website but weren't ready to quite make it live yet so we could simply go to our projects URLs file so let me open that up here and I could simply create a path instead of blog I could change this to blog underscore dev and with that one change if we go back to our browser here let me open this up then now in order to access my blog I would have to go to forward slash blog underscore dev and that takes me to the home page and to get to the about page its blog dev ford slash about and that takes me to the about page so now we can see that all of our blog routes are accessible through this blog dev route now and I didn't even have to change anything within our actual blog application I only changed the one project path in the URL pad in URLs patterns so that's extremely useful to just be able to change that in one place for your entire blog application ok so just a few more things before we move on to the next topic so first of all you probably noticed that I've been put

put trailing slashes onto the end of my url patterns

trailing slashes onto the end of my url patterns so for example at the end of admin we have a forge slash here and after blog dev I put a trailing forward slash there as well so why did I do that and can we leave it off well I think it's a good idea to leave it there because by default if it has a trailing slash then Django will redirect routes without a forward slash or without a trailing slash to that route that has one so both this blog dev without a trailing slash and blog dev with a trailing slash will get redirected to the blog routes and that's usually what we want and web sites so that no one ever gets confused about what routes are not returning the same results okay so lastly what if we wanted to our blog to actually be the home page of our entire web site so right now we have to go to blog underscore dev to get to the home page of our blog but what if we just wanted to be able to go to the home page of our website so just localhost port 8000 is what it is right now and see the home page of our blog from there so in order to do that within our project URLs we can just simply leave the path to our blog URLs empty so I will get rid of that and save it and by doing that it will match the empty path and our project URLs and also blog URLs and just return at the blog home page so now with that change if we open back up our browser and just go to the root of our website so localhost port 8000 if I run that then now the blog homepage is what we see and if we go to just forge slash about then we get the blog about page so I'm gonna leave our routes like this because I want to make our blog the home page of our entire website but you can add a non empty path there in the project URLs if you'd like that's completely up to you okay so I think that is gonna do it for this video hopefully now you have a pretty good idea for how basic routing is going to be working in Jango and in the next video we'll learn how to return some more complicated HTML code using templates and also how to pass variables to our templates but if you have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them there are several ways you can do that the easiest ways to simply like the video and give it a thumbs-up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you could contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

Методичка по этому видео

Структурированный конспект

Django: приложения и маршрутизация URL — полное руководство

Создание приложений в Django и настройка URL-маршрутов. Как организовать структуру проекта, создать представления и связать их с URL-адресами.

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник