Delete Blog Post

Finally, to complete the basic CRUD operations, the delete functionality can be added. This only needs one simple function.

Add the following POST function to delete a post. Note that this function also uses a path parameter, the id of a blog post. You’ll need to import the delete_blogpost_by_id_api function:

web/views/blog_views.pypython
from api.blog_apis import get_blogpost_by_id_api, create_blogpost_api, update_blogpost_api, delete_blogpost_by_id_api  # UPDATED
web/views/blog_views.pypython
@router.post('/blog/delete/{id}', response_class=HTMLResponse)
def blogpost_delete_post_view(*, id: uuid.UUID, session: Session = Depends(get_session_db)):
    delete_blogpost_by_id_api(id=id, session=session)
    return RedirectResponse('/', status_code=status.HTTP_303_SEE_OTHER)

Why POST and not a simple link (a GET)? GET requests are supposed to be safe: they read things and never change them. Browsers prefetch links, crawlers follow them, and another website can trigger a GET just by embedding an image tag with your URL. None of those should be able to delete a blog post. A form that POSTs is only sent when someone presses its button.

Update the blogpost.html template to also include a delete button. It’s a small form that posts to the delete URL, with a touch of JavaScript to ask whether the user is sure:

web/templates/blogpost.htmljinja
<header class="intro-header" style="background-image: url('{{ context.post.cover_image }}')">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <h1>{{ context.post.title }}</h1>
                    <h2 class="subheading">{{ context.post.teaser }}</h2>
                    <span class="meta">Posted on {{ context.post.created_date.strftime('%d %B %Y') }}</span>
                    <br>
                    <a href="/blog/update/{{ context.post.id }}" class="btn btn-default">Edit</a>
                    <form action="/blog/delete/{{ context.post.id }}" method="post" style="display: inline"
                          onsubmit="return confirm('Are you sure?')">  <!-- NEW -->
                        <button type="submit" class="btn btn-default">Delete</button>  <!-- NEW -->
                    </form>  <!-- NEW -->
                </div>
            </div>
        </div>
    </div>
</header>

And there you have it, the rest of this section deals with adding usefulness and improving on what we already have. For example, including a Markdown editor for the content and the ability to upload and resize images.