Python Django Tutorial: Full-Featured Web App Part 10 - Create, Update, and Delete Posts
53:14

Python Django Tutorial: Full-Featured Web App Part 10 - Create, Update, and Delete Posts

Corey Schafer 31.08.2018 379 571 просмотров 8 008 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Django Tutorial, we will be learning how to use class-based views in order to create, update, and delete posts. These class-based views are very convenient once we get used to using them properly. 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

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

Introduction

hey there how's it going everybody in this video we'll be adding the ability for users to add posts that will then show up on the home page will also look at using class-based views in order to work with our post model and see how these class-based views can be useful so let's go ahead and get started so now that we'll be working with our blog post we're going to be going back to our blog app that we created earlier in this series so first things first I'm going to open up the blog views and we're going to look at using class-based views in order to display update and delete new post so within our blog app let's open up views dot pi and this is where

Classbased views

we have our current home and about views so far in this series we've been using function based views and we should be fairly familiar with these by now so our URL patterns are directed to a certain view which are these functions and the views then handle the logic for the routes and then render our templates so now there are these things called class-based views and those have a lot more built-in functionality that we'll try to handle a lot of the backend logic for us so I'm going to create a class-based view for our home page so that we can see what this looks like compared to a function view so first of all there are different kinds of class-based views there are list views detail views create views update views and delete views and a couple more so if we think about it a lot of websites have very similar functionality so take a blog for example so you're going to have a web page where it lists all of your blog posts so this would be a list view or if you think about a site like YouTube for example then there's going to be a subscriptions page where it lists all of your video subscriptions so that is also a list view now what would happen if we clicked on one of those blogs or videos from the list well then it would take us directly to that blog or to that video and give us more details and it would show us all of the content the descriptions comments and all of that so those details that would be a detail view and then we also have the ability to update and delete blogs or videos and those would be update and delete views so Gengo tries to predict this common behavior and give us these generic views that do a lot of the background work for us so right now we have a homepage that gets all of our post objects and passes them to our home dot HTML template to display all of them there so that would be a good candidate for a list view since our home page is listing all of our blog posts so I'm going to rewrite this as a list view so that you can see the difference between that and the current function that we have right now so first I'll import list view up here at the top by saying from Django dot views let me spell that right dot generic import list view and now I'm going to create a new class because remember these are class-based views and I'm going to call

Create a new class

this so I'll create it right below our home function so that we can see the differences here so I will call this class post list view and I will inherit from that list view and within our list view we need to create a variable called model and this will tell our list view what model to query in order to create the list and in this case we want it to be all of our posts so we'll set that model equal to post now technically this is all that we need to do in order to create a list view but we're going to need to add a little bit more to do this but first let me show you what this does if we try to use this list view like it is now and why we need to add a little bit more so in order to use this list view we can open up our blog URLs dot pi module and say that we want to use this post list view instead of our current home function so within our blog app let's open up those URLs and instead of using

Create a classbased view

this views dot home we're instead going to use our post list view so let me actually import that directly so I'll keep the view import that we have now but I'll also add a direct import so I'll say from dot views import post list view and now instead of using our home view I'm going to replace this here with this post list view now when we use class-based views we can't just pass in the class like this it has to be converted into an actual view and they have a method available that does this that's called as view so we need to add that on so I'll say dot as underscore view and then we need to actually execute that okay so now let's load this in our browser and see what this does now it's not going to work right now but let's look at the error that we get so first of all it looks like our test the server is running so now let me reload our home page here so we can see that it says that a template doesn't exist so by default class-based views look for templates of a certain naming pattern so we can see here that it is looking for blog ford slash post underscore list dot HTML so let me write this out so that you can see this a little bit better so this is looking for a template with the naming convention of the app and then Forge slash the model and then underscore and then the view type dot HTML so in this case since our app is blog it was looking in blog and then post is the model so it was looking in post underscore and then the view type is list so altogether it was looking for blog forged slash post underscore list dot HTML so we could create a template with this naming convention and it would see that template but we can also change which template that we want this view to use and since we already have a template for our home view let's go ahead and just do that and change the template that it's looking for so we can do that within the view spy so I'm going to copy this just as a reference go back to our view spy and I will paste this in and

Create a new template

now let's set a new template so that we can use our existing template for our home page so I will say template underscore name is equal to blog forge slash home dot HTML and I'll just put this convention on the of the line there so that we have that as a reference okay and lastly even with this change in place this isn't going to work for us just yet because it doesn't know what we want the variable to be named in our template that we're going to be looping over so for example if we look up here in our home view function we called all of our post objects post in our context but by default our list view is going to call that variable object list instead of post so we can either go into our template and change it so that it's looping over object list or we can set one more variable in our list view and let the class know that we want that variable to be called post instead so since we already have the template created let's just go ahead and set this variable here within our list view so to change that we can set an attribute here and this will be called context underscore object underscore name and we will set that equal to post since that's what it is up here in our home template and just setting those three attributes should do it so now if we save those changes and then reload this in our browser so reload our home page then now we can see that we got the same thing as when we were using our function view now one thing that isn't really right about our blog right now is the ordering of our post so our first blog post at the top is actually our oldest one and our latest post that we created is at the bottom now that's probably not what we want so if you're looking at someone's tweets or updates then you probably want to see their latest ones at the top instead of needing to scroll all the way to the bottom to see their latest so let's fix this so in order to do this we're going to need to change the order our query is making to the database so let's open up our view spy and go into

Change post order

our list and inside of our list view in order to change the order it's as simple as adding an ordering attribute with the field that we want to order on so I will say I will create a new attribute here called ordering and set this equal to and we want to date hosted now this will order our posts from oldest to newest like it's doing right now if we want to go from newest to oldest then we can just put a minus sign here at the front so now with that one small change if we save that and then go back to our browser and reload this then we can see that our newest post is at the top and that blog one which is our oldest post is at the bottom ok so now we are using this list view instead of our older function view so now let's look at the differences

Difference between function and list views

between those views that we have here so here was our home function and here is our home list view so we can see that we're not really saving any lines of code in this example compared to the function view but in our class base view we are basically just setting some variables and in our function view we had to actually render a function and explicitly pass in that information now we could have saved some lines of code if we had used generic view defaults so if I had created a template with the naming convention that our list view was looking for and used the variable name of object list inside of our template as opposed to post like we're using here then really the only line of code that we would have needed to set is the model and also the ordering if we wanted the ordering to be correct so really you can actually get a working class based view with just a single line of code if you stick to the conventions perfectly so let's actually do this with our next class base view and stick to the conventions so that we can see how this cuts down on code ok so to do this let's create a view for individual posts now when we look at an individual post this is going to be a detail view since we're going to be looking at the details of a single post object so to create a detail view let's first import it so up here at the top where we imported ListView it's also import detail view and now down

PostDetailView

here underneath my post ListView let's actually copy this and paste another class beneath here and now let's change a couple of things so instead of this being post ListView will call this post detail view we're going to import from detail view instead of ListView and now I'm also going to get rid of the ordering the context object name and the template name and I'm only going to leave the line with the model set to post okay so with that model set the post let's go create the URL pattern so let's open up our URLs now first

PostDetailView Route

we'll need to import that post detail view so up here at the top let's import post detail view and now we need to create a route that takes us to a specific post and to do this we're going to use something that we haven't seen yet so we have to create a URL pattern that contains a variable so for example let's say that we wanted to view the page for blog one then that URL would be something like post ford slash one and to go to blog two it would be something like post ford slash two and django gives us the ability to add variables within our actual routes so if we wanted to create a route where the ID of a post is actually part of the route then we can create a route that looks like this so I'm going to copy this home route as a starting point and paste this in and now we can create a route with a variable just by saying okay post forged slash and then these angle brackets here and then we can say PK and that is going to be the primary key of the post that we want to view so if we go to post forged slash one then we will go to the blog with the ID of one or with the primary key of one now we can also set what kind of variable this is so if we know that this is going to be an integer then we can tell Django that we only expect to see integers after post so that will prevent you know put somebody putting in strings or anything like that now remember we want to end all of our routes with a trailing slash and now instead of going to post list view the post detail view is what is going to handle this route and instead of this being blog home we will make this post - detail so again by specifying that PK variable in the URL that allows us to grab that value from the you and use it in our view function and in this case we're using a class-based view so that will be passed to the class-based view and remember how I said we're going to stick to conventions so that we can save some lines of code well the reason that I called this variable PK is because that's what the detailed view expects it to be in order to go grab that specific object so we could change that by adding an attribute to our class but if we leave it as PK then we can just leave it as is okay so lastly we need to create a template that will display our post details now if I go back to my views here then we can see

PostDetailView Template

that by default our generic class-based view are going to be looking for a template with this naming convention so it's going to be looking in the directory of the app name which in this case is going to be blog and then a template with the model name which is going to be post then an underscore and then the template type or and then the view type so in this case it's going to be detail so this is going to be looking for a template called blog forged slash post underscore detail HTML so let's create a template with that name so that it finds it automatically without us needing to specify a template name like we did in the post list view so within our templates I'm going to open the subdirectory of blog and within blog let's create a new template and I will call this post underscore detail dot HTML and this is going to be very similar to home dot HTML except we're just gonna have a single post so let me copy home dot HTML and paste this in to post detail but the difference here is that we don't need to loop over posts since there's only going to be one so I'm going to remove our for loop here and remember there is an end to the for loop down here and now I will uninvent this and fix this let me fix the indentation here and there are just a couple more changes here so for example we don't need the title of our post to be a link anymore because that link on the home page is what takes us to the detailed view so now we can just leave it as an h2 tag but I still want this article title class here so I'm going to copy that article title class but now we can just remove the anchor tag so I'm gonna remove the closing anchor tag there and remove this whole opening anchor tag here and then I'm going to paste that class into our h2 tag there instead okay and just one more change that we need to make so when we're dealing with detail views it expects the context of this template to be called object so right now we are calling this post now we can change this to post by changing an attribute in our class but like I said we're gonna try to keep to all of the defaults that it expects so let's instead change all of these post variables here to use object instead so where we are printing out the image URL here I'm going to say object dot author and for the author I'm gonna say object author for the date posted we'll do object date posted for the title we will say object dot title and for the content object dot content and I think that is the last one okay so now let's save this and open a post in our browser and see if this is working so first I will check the dev server and that is running and now let's go to a URL for a specific post so I will do ford slash post forge slash one and we can see that displays our blog one so now we can see that we've got pages specifically for these individual posts now remember in our views all we needed was to specify that model on our detail view and it handled the rest of that functionality for us okay so now that we actually have these individual pages let's add links to these routes for the individual posts on our home page so right now those are just dead links because I was waiting until we got the detail routes working so if we go to the home page right now we can see that these actually go nowhere so let's update these links to where they actually go to the page for that individual post so those are within the home dot HTML template because that is where we are looping for these posts so I will open up home dot HTML and here is the post title that is where we have this link and currently it is a dead link so in order to link to that individual post we can use the URL tag that we've seen before so I'll say URL and the name of that route was post detail and now we also had a parameter in that URL so remember it's the ID for the individual post so we can pass that into the route just by adding this on to the URL tag here so I'll say post dot ID and that'll make sure that gets passed in if I go to our URLs

Testing PostDetailView

that'll get passed in as the primary key here in the URL so now let's go back to our browser and reload our homepage and now if I hover over these this is hard to see but in the bottom left it's telling me that the link is going to take me to post - this one will one and this one will go to post three so if we test some of these then we can see that those are now working now if I try to go to a post that doesn't exist then I should get a 404 error that means that the post with that ID doesn't exist so if I go up and try to go to let's see instead I'll go to post 10 instead of post 1 now we don't have a post 10 so we can see here that this says page not found 404 and that's good that we get that error because that route wouldn't exist unless we had a post with that ID ok so now we've seen a list view to list our posts and a detail view to get a specific post now let's create a create update and delete view so that we can do all of those things with posts on the front end so first let's see how users can create new post so let's open back up our views here so

Creating PostCreateView

I have the views open here I'll scroll up to the top because we need to import our create view so right after a detail view I will import create view now we can see that our import line here is starting to get a little long if you ever want to break up an import line then you can just put these within paren here and put these on different lines so I will move all of those and then in the parenthesis okay so now for this create view I'm just going to copy the detail view and modify it a bit so I will copy the detail view and right underneath I will paste another class and instead we'll call this post create view and we will inherit from create view okay so this is going to be a view with a form where we create a new post so the only other thing that we need to provide are the fields that we want to be in that form so let's say that we want to fill in the title and the content for a new post now the date posted will be filled in automatically and we'll see how to set the author in just a second but for now we need to set the fields that we want in that form so I'll say fields are equal to and we just want the title and the content and save that okay so with that in place let's update our URLs with this new create view so within our URLs I will import post create view and just like in our views I'm going to split these up on multiple lines because this is getting a little long now don't forget the parentheses around those okay and now we'll create the URL pattern for creating a new post so I'm just going to copy this line here and then change this around a little bit so to create a new post we'll go to post forge slash new and the posts are and the view to handle that will be our post create view and instead of post detail we will call this post create okay so at this point we know that we need a template for this view but it might not be named what you think it's going to be named so for example for the detailed view it was post underscore detail so you might think that for this one it should be post underscore create but this one will actually share a template with the update view that we're going to be creating and a little bit so they actually expect this template to be the name of the model followed by underscore form so in this example we're going to create a template called post underscore form so up in my blog templates I'm going to create a new file and let's create this called post underscore form dot HTML and this form template is going to be really similar to the other templates that contain forms that we've created in this series so far so actually it would save us time just to grab our register template because there will only be a few changes that we need to make from that so within our users app I'm going to go to those templates and I'm gonna open the

Creating PostForm Template

register template and copy that as a starting point and paste that in to our post form template okay so our create view actually expects the form to be called form so we can just leave that as is and we'll be printing that form out using the krispy forms like we've done before so all we need to do is change the legend and the submit button and we can also remove this link down here at the bottom so first I'll change the legend so I'll change this to blog posts and still be creating a blog post for the submit button I will change this to post and this link contained in this div right here that says already have an account we don't need that link there so we can just remove this entire div underneath our form so now we only have the form on this page so let's save that okay so with that template created let's see how this actually looks in the browser so I will open this up and go back to our home page and now I'm going to go to the route of ford slash post ford slash new and we can see that it is a form to create a new blog post ok so this is looking really good so this is why class-based views are so powerful because we didn't have to actually create a forms module to create this form or anything like that all we did was tell our create view that we wanted to work with the post model and also that we wanted to have the title and the content fields within that form now it's not a hundred percent perfect because there are still some changes that we need to make so for example if we try to create a new post right now then it's not going to work so if I come in here and say I title of blog 4 and then my fourth vlog post and if we submit that then we can see that

Setting the Author

we're getting an error here and it says that this is an integrity error not null constraint failed it has no blog post our ID and the reason that we're getting an integrity err is because we're trying to create a post but it's saying that our author is null and that's not allowed so every post needs to have an author now we want the author of the post to be the current logged in user but it doesn't know that so we have to tell it in some way so the way that we can do that is to override the forum valid method for our create view and that will allow us to add the author before the form is submitted so let's do that now so back in our views so I'm going to go to our blog views here and down to our post create view and within this create view we need to override the forum valid method so I will create a method here that is forum valid and this takes in self and form as arguments and within here we can simply set the author on the forum by saying forum dot instance dot author is equal to self dot request dot user so basically this is saying hey that forum that you are trying to submit before you do that take that instance and set the author equal to the current logged end user and once we do that then we can validate the forum so we will return super dot form underscore valid and then pass in that form as an argument so basically this line here is just running that form valid method on our parent class and that would have been run anyway but whenever we over ride it right here we are just setting the author before that gets ran okay so that should do it for setting the author so now let's try to create a new post and a browser and see what we get now I'm going to let you know that this still isn't going to work but let's look at the air and see if it is helpful so we'll go back to the post ford / new and try to create another post so fourth post and submit okay so we're no longer getting the integrity err about the author so that's good now we're getting an error that says that we don't have a redirect URL it says in the error message I know this is a little small here it says either provide a URL to redirect to or define a get absolute URL method on the model so basically it's telling us that it created the post successively but it doesn't know where we want to be redirected to now so if we go back to the home page then we can see that our post was actually created here so that's good so now to get this working 100% we just need to let the view know where we want to redirect once we've created the post now ideally we would just redirect to the detail page of the post that we just created and that's actually what it tries to do but it just doesn't know how to get there so we have to tell it and it said this on the error page but the way to tell Gengo how to find the URL of a model object is to create a get absolute URL method in our model that returns the path to any specific instance so let's open up our blog models and I'll show you what I mean by this so let's open up our blog models so

Get Absolute URL

in our blog app I'm going to open up models dot py and within our post model we need to create that get absolute URL method so that Django knows how to find the location to a specific post so first we're going to be getting the URL of a particular route and in order to do this we need to use the reverse function now you might be wondering why we're not using the redirect function that we've seen earlier in this series but redirect and reverse are a little different so redirect will actually redirect you to a specific route but reverse will simply return the full URL to that route as a string so that is the difference between those and in this case we simply want to return the URL as a string and let the view handle the redirect for us so first we have to import the reverse function so up here at the top I'm going to say from Django dot URLs import reverse and now down in our post model now we'll create that get absolute URL method to tell Django how to find the URL to any specific instance of a post so to do this we can say get absolute underscore URL and this will take self as an argument and now we can return the path to a specific post so we're going to return reverse so like I said reverse will return the full path as a string so the full path that we want to get is the path to the post - detail route and it remember it needs a specific post with a primary key so we will set our Korg's equal to and remember that URL parameter is called pk for primary key and the value for that is going to be self dot pk so the instance of a specific post primary key okay so now if we save that then now let's try to create one more post and hopefully with these changes this will be working fully so let's open up the browser here and I'm going to go to forge / post Ford / new and I will create blog 5 and then my fifth post and I will submit that and we can see that it created our post and redirected us right to the detail page for the post that we just created so that's great now if you just want that to go to the home page instead of the specific post then you could set an attribute in the create view called success URL and just set that to the home page instead but in our case I think it's better to redirect to this detailed view okay so that is a lot of functionality that Django gives us after filling in just a few different attributes and that would have taken a lot more work and other frameworks now that would have also taken a lot more code if we'd done that with regular function views instead so we would have needed to create forms and handle post requests and save the information and all of that but with these class-based views we can do a lot of this just by knowing what attributes need to be set so you can definitely save yourself a lot of lines of code once you get familiar with this kind of stuff okay now there's actually one more thing that we need to do with this create view so we shouldn't be able to create a post unless we're logged in as some user so we need to make it so that if we try to access this route and we're not logged in then we'll just be redirected to the login page now we saw how to do this with function based views when we created our user profile page so for function based views we use that log-in required decorator well we can't use decorators on classes so what we are going to use here is something called a login mixin and that's basically just a class that we inherit from that will add that login functionality to the view so let's go ahead and add this in so I'm going to go back to our views here and go up to the top because we need to import this and here at the top I will import this by saying from Django dot country birth mix-ins import and this is kind of long login required mix in and now we just want to add this to the classes that we are inheriting from and we'll want to add this to the very first one on the far left so I'm going to copy this and go down to our post create view and we want to add this to the far left so we want to inherit from the login required mixin and then the create view so now if we save that and go back to our browser and log out and then try to add a new post so I'll log out and then I will go to post ford slash new and then you can see that we are redirected to the login page so that's good okay so now let's create an update view so that we can update posts on the front end so we should kind of be getting used to this by now so let's go back to the views here and at the top we will add to our list of imports so I will import an update view and now down here under our create view I'm just going to copy our create view because the update view is going to be very similar so I will paste that and I will let's see make all this post update view here and we want to import from update view and now we can actually leave this exactly the same in terms of the model and fields and the form save method so let's add a path now to our URL patterns so let's go to our urls dot pi and we can just copy our actually let me copy the post detail view here well and let's also not forget to import the view that we just created so we created that post update view so now let's do the route for this so i copied the post detail view and pasted that and here now to update a post we're going to need to include that primary key with that route as well because we have to know what post that we are updating so we will do post forged slash this primary key and then after that we will do ford slash update and we will let the post update view handle that route and for the name here we will do post - update ok and since we are providing that primary key in the URL to the post that we want to update then Gengo the Django update view will take care of everything else with the information that we've already provided and even for the template it's just going to use that same post form template that we created for the create view so if we don't even need to add another template and so now this should be working so if I open up the browser and I try to update a post so let's up go to the browser here and login so I'll log in as a user and now let's try to update our one of our posts so I'll go to this blog 5 and then go to forge / update after post 5 then we can see that we get a forum and this is already filled in with the current title and content so let's try to update this so I'll say blog 5 updated my fifth updated post and submit that so we can see that updates our post so that was pretty easy to put together now when you're building an application like this you kind of need to be thinking about the different ways that people could use your app or try to abuse it and always try to plan for that so for example right now we have a login check on being able to update a post and to be able to create a post but we aren't checking if the author of the post is the person trying to access this update page and that's important because we only want the people who wrote the post to be able to edit it so let me show you what I mean if I go to the home page and then I click on a blog written by another user so this test user here as blog 3 if I go to that and then type an update after post 3 then we can see that we can also update this blog entry so that's not good so that would be like if someone could edit your tweets or something like that so we want to put a check in place so that only the author of the post can actually update it so to do this we're going to use another mix in and first we have to import it so let's go back to our views and go up to the top here to our imports and I'm going to import a mixin called user passes test mixin and now let's add this to our update view inheritance so I will copy that and go down to our update view here and I will add this to our inheritance so it still needs to be to the left of the update view so I'll just put it right after the login required mix in there and once we have that in place we can create a method called test funk and that is a function that our user passes test mixin will run in order to see if our user passes a certain test condition so I'll just create this underneath the form valid method that we have already created so I will say def test underscore funk is what we need to call that and it takes self as the argument there and now we want to get the exact post that we're currently updating the way that we can get this is using a method of the update view called get object so we can get the post by saying post is equal to self get object and that will get the post that we are currently trying to update and that's actually a method so we need to put the parentheses on there and now we can check to make sure that the current user is the author of the post so I'll say if self dot request dot user is equal to post dot author so this gets the current logged end user and it's checking if this is equal to the author of the post that we are trying to update so if that is true then we want to allow them to update the post so we can just return true and otherwise if that conditional is not met then we will just return false now we could just return that conditional as one line right there but I think this is a little bit more readable how we have it now okay so with that test function in place that should prevent any users from trying to update other people's posts so let's go back to our browser and reload the page where we were trying to update someone else's post so this is currently test users post so if I reload this then we can see that we get a 404 or 403 response that says that this is forbidden and that is the exact response that we want so that is good okay so that does it for the update view so lastly we're also going to want to create a delete view for deleting posts and the delete view is very similar to our detail view so I'm going to go back to our views and import our delete view

Delete View

so let's go back to our views here and let's import the delete view from here at the top so we'll add that in and like I said this will be very similar to the detail view so let's just reuse that so I will grab the post detail view and I'll put this underneath our update view here so now we just want to change this to say post delete view and we want to inherit from delete view now unlike our detail view we want to require a user to be logged in here and also require that the user is the author of the post in order to see the delete view so we'll just copy those inherited mix-ins from our update view so I will go up to our update view here just grab now login required mixin and the user passes test mix in and paste those in there and just a reminder those have to be to the left of the delete view inheritance and now will also copy the test function from our update view since that will be exactly the same we're going to be running that same test of making sure that current post has the author of the current logged in at user okay so now all we need to do is add a path to

Delete Path

our URL patterns so I'll open up our urls go up here and import that post to leave you so import post delete view and now let's create a delete path so I'll copy our update view here so we want this to be the post forged slash primary key forged slash delete and we want to send this to the delete view and the name that we want here is going to be post delete okay so now all this needs is a template and the template that this expects is just a form that asks if we're sure that we want to delete the post and if we submit the form then the post will be deleted so let's create this so this template is going to be similar to the others except it's going to be called post underscore confirm underscore delete dot HTML so within our blog templates I'm going to create a new file and this is called post underscore

Delete Post

confirm underscore delete dot HTML and I'm just going to copy from our post form template that was used for our create and update templates so I am going to copy from here and paste that into our post confirm delete template and now we'll make a couple of changes here so the legend instead of this being blog post I'm going to change this to delete post as the legend now this doesn't actually pass in a forum for us so we can actually remove the crispy forms and they form line here so I will remove where we are loading in crispy forms and I will also remove our form line so really this is just going to be a page that asked us if we really want to delete the post and if we hit the submit button then the post requests we'll simply delete the post so we just have to ask the user so underneath the legend here I'm just going to put in an h2 tag and I'm just going to say our whoops are you sure you want to delete the post and then we will actually just put in the title for the post so they know which post they are about to delete so remember the context here is called object just like the detail view so we can say object dot title and now for our buttons at the bottom we currently have one that says post so this is the submit button this is what will confirm the deletion so let's be sure that the user knows this so in this button we will say yes delete and let's also give this a class of outline danger instead of info because deletions should have a visual warning since its permanent so instead of this being outline info I will say outline danger and now let's also put a cancel link that takes them back to the post detail view just in case they didn't mean to delete this post or change their mind so I'm going to copy our button here but after I copy this so let me paste another button underneath here but now I'm going to change this to an anchor tag so instead of a button that will submit we will change this to an anchor tag and also remove this type equals submit there now like I said we want this to be a cancel button so I will change the text in here to be canceled and we want to set an href that just takes us back to the detailed view of this exact post so to do that within our href we can put in a code block here and say URL and we want to go to the URL of post detail and to pass in the primary key of this post we can just say object dot ID so that will create a URL of the post detail page for this post ID and then lastly instead of outlining this in danger we only want the danger one to be the confirmation of the deletion for the cancel we'll just make this more muted so a good bootstrap style for this is secondary so we'll say button outline at - secondary okay so that should do it so

Testing

let's bring up our browser and see if this works so if we go to our browser then I can go back to our home page here and find a post that we have written and now I will try to go to forge / delete and it says are you sure that you want to delete the post blog 5 updated so if we say cancel then it should take us back to that post page which it did so now let's go back to the delete route but now if we say yes that we want to delete this post and click on that then we can see that we get an error and because it's saying that it doesn't know where to redirect us now if we read the error then it actually tells us exactly what we need to do it says that we need to provide a success URL so we'll go do that now when we get a failure on deletion it actually doesn't do the deletion just in case so that post will still be there so if I go back to the home page then we can see that

Success URL

post still exists so now I'm going to go back to our delete view and add a success URL so that our deletion knows where to redirect us if that works so let's go back to our blog views so I will open up our views dot PI and go down to our delete view and in our delete view all we need to do is add a success URL attribute and we'll just set this to the home page so it can't go to the page of that post like our create and update views did because that post is deleted and no longer there so the home page sounds like a good place to send them so we will just say success underscore URL is equal to and we'll just send them to the home page ok so now let's open that post and try to delete that again so I am going to go back to the home page here let's click on blog 5 and I will go to vlog 5 forge slash delete and it says are you sure you want to delete this post will click yes and we can see that post was now deleted okay so that works so that is great so in this one video we've added the ability to list view create update and delete posts using these new class-based views so that is a lot of functionality that we were able to add in here during the short time of this video so now that we have all of this working let's make a few changes to our site just to get everything working together a bit better so right now all of this functionality is working but we don't have any links in place to actually get to any of these routes that we just created so let's create those so first of all let's put a link in our navigation bar to create a new post so our navigation bar is in the base HTML template of our blog so let's open that up so I will go to our blog templates and open up base HTML and if we scroll down to our navigation which is right here then I'm gonna add this to the part of our navigation that the user can only see if they are logged in so that is this section right here so I'm just going to copy this profile link and paste this in and then change this so instead I want this to be a URL for post - create and we want the link text just to say new post ok so now we have a link to create a new post so now let's add links to update and delete our post so I think a good place for these would be within the post detail page and if the user is the user who wrote the post then they'll see links to update and delete the post if they'd like so that will be in the post detail template so within our blog templates let's open up the post detail template and let's just put these buttons right after the author and the date so date here we can put in a conditional so we will say if object dot author is equal to user which is the current logged in user then we can add in the buttons for the update and delete so first I'm going to end this if statement so end if and now within this conditional if the author is the current logged in user then we can add these links to update and delete so I'll add an href here and we want this to be a URL so we'll say URL and this will be a URL to the post - update route and we need to tell which object we want to update so this will be object dot ID and it'll pass that in to the URL correctly and for the link text here we will just say update now let's also give this some classes so we'll say class is equal to B TN which is a bootstrap button and we also say BTN - secondary that's kind of a more muted button for update and let's also give this a class of BTN - SM which is a smaller button and also I want a margin top of one so MT - one and a margin bottom of one as well so MB - one in case you guys were wondering I've kind of played around with these styles before I recorded this video so that's how I know what how I want these to look so now I'm going to copy this anchor tag here and now let's make the delete button so right underneath the update button I will paste in a new link here and we will have this be a delete button and we want this to go to post delete for the URL and for the class here instead of this being button secondary let's make this button danger so that they know that this is a delete button okay so with those changes in place we should have links to all of the routes that we created in the video so let's give this one last look in the browser so we will save all of those and open this up in the browser so we can see that since I'm logged in we now have a new post link up here so if I click on that then it takes us to the route where we can create a new post so if I go back to the home page and click on a post that I have created then we can see that we have an update and delete link here if I like on update then we can see it takes us to the update route if I click on the delete link then it takes us to the delete route now there's one more thing with this post detail template here I actually wanted these to be on a new line so I think I forgot to wrap those in a div so let me open that back up luckily that was the last thing we were just looking at so these two buttons here inside this conditional and our post detail template let's actually wrap those in a div so I will create a div there and now let's just put those inside of there and fix that indentation now let's reload this okay now we can see that those buttons are underneath there and I think that looks a lot better now let's also make sure that conditional is working by going to a post that someone else has written and when we go to that post detail we can see that the update and delete links aren't there so that conditional is working okay so I think that is going to do it for this video hopefully now you have a pretty good idea for how you can use class-based views to list out different objects from our database and also how to view update and delete those objects using these views now in the next video we'll learn how to paginate our site so that our posts are broken up into different pages and we'll also see how to create a page for specific users posts 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 then 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 can 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 you

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

Ctrl+V

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

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

Подписаться

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

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