Git Commit: deleting a blog post
In order to delete a blog post, I am planning to add a delete button to the detail view of a blog post. Browsers don't understand that I have to send a delete request when the button is clicked. So, we are going to catch the get request on button click and use it to identify and delete the blog.
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="row">
<p class="text-secondary my-4">{{blog.content}}</p>
<!--previous content above-->
<a href="/delete/{{blog.id}}" class="btn btn-outline-danger col-sm-1 justify-content-center">Delete</a>
</div>
</div>
{% endblock %}
Now, all we need to do is to have a route that deletes the blog with the given id and informs the end-user about the result.
from db.repository.blog import delete_blog
##
@router.get("/delete/{id}")
def delete_a_blog(request: Request,id: int, db:Session = Depends(get_db)):
token = request.cookies.get("access_token")
_, token = get_authorization_scheme_param(token)
try:
author = get_current_user(token=token, db=db)
msg = delete_blog(id=id,author_id=author.id,db=db)
alert = msg.get("error") or msg.get("msg")
return responses.RedirectResponse(
f"/?alert={alert}", status_code=status.HTTP_302_FOUND
)
except Exception as e:
print(f"Exception raised while deleting {e}")
blog = retreive_blog(id=id,db=db)
return templates.TemplateResponse("blog/detail.html",{"request":request,"alert":"Please Login Again",
"blog":blog})
Notice, we are also sending an alert at the last line, but our detail.html does not handle alerts. In order to do this, I would like to move the alert handling logic to base.html
<!doctype html>
<html lang="en">
<body>
{% include "components/navbar.html" %}
{% with alert=alert %}
{% include "components/alert.html" %}
{% endwith %}
<!--previous content -->
Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.
We know, we might make it hard for you but definitely worth the efforts.
© Copyright 2022-23 Team FastAPITutorial