Update Blog Post
NotesAdding the “update” functionality is very similar to what we just did for adding the “create” components. The key difference being that a database record needs retrieving when rendering the web form so all the fields can be prepopulated. And naturally, this time we’ll be exploiting the update_blogpost_api function instead.
When working with anything, it’s best always to be as explicit as possible. It may be tempting to reuse the same form for both create and update, but keeping things separate avoids confusion. You may see some developers being obsessive with reuse and inheritance but in reality code isn’t physically huge, we’re not dealing with large media files here right? It’s just text. So, Keep things clear rather than clever! (You’ll thank me for it when projects get large and more complex.)
Add the following function which is the GET request for the update form, and note that this function uses a path parameter using the id of a blog post:
@router.get('/blog/update/{id}', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_update_get_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
post = get_blogpost_by_id_api(id=id, session=session)
context = {
"page": "blog_update",
"post": post
}
return templates.TemplateResponse(request, 'blog_update.html', {'context': context})The GET function does a lookup and returns the post to be edited. Add the following template with a form that includes the current values. The id of the post is part of the form’s action URL, so the POST function receives it as a path parameter, just like the GET:
{% extends "_base.html" %}
{% block content %}
<!-- Page Header -->
<header class="intro-header" style="background-image: url('/static/img/contact-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Update</h1>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>Complete the form to update blog post:</p>
<form action="/blog/update/{{ context.post.id }}" method="post">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Title</label>
<input type="text" class="form-control" placeholder="Title" id="title" name="title"
value="{{ context.post.title }}" required>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Teaser</label>
<input type="text" class="form-control" placeholder="Teaser" id="teaser" name="teaser"
value="{{ context.post.teaser }}" required>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Content</label>
<textarea class="form-control" placeholder="Content" id="content" name="content"
required>{{ context.post.content }}</textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Cover Image</label>
<input type="text" class="form-control" placeholder="Cover Image" id="cover_image"
name="cover_image" value="{{ context.post.cover_image }}" required>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Published</label>
<input name="published" id="published" type="checkbox" {% if context.post.published %}checked{% endif %}>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
<hr>
{% endblock %}Jinja2 escapes the values it inserts, so a title containing quotes or < characters can’t break out of the value="..." attribute.
And now add the POST function which exploits the update_blogpost_api function from the APIs. This function also uses the RedirectResponse, this time back to the updated post:
from api.blog_apis import get_blogpost_by_id_api, create_blogpost_api, update_blogpost_api # UPDATED@router.post('/blog/update/{id}', response_class=HTMLResponse)
def blogpost_update_post_view(*,
id: uuid.UUID,
title: str = Form(...),
teaser: str = Form(...),
content: str = Form(...),
cover_image: str = Form(...),
published: bool = Form(False),
session: Session = Depends(get_session_db)):
blogpost_updates = BlogPostIn(title=title, teaser=teaser, content=content,
cover_image=cover_image, published=published)
update_blogpost_api(id=id, data=blogpost_updates, session=session)
return RedirectResponse(f'/blog/{id}', status_code=status.HTTP_303_SEE_OTHER)Both update routes start with /blog/update/, so they don’t clash with /blog/{id}, wherever they are in the file.
To use this new functionality, add a link to the blogpost.html template. This way the link can be dynamically added using the id of the blog post, for example:
<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> <!-- NEW -->
<a href="/blog/update/{{ context.post.id }}" class="btn btn-default">Edit</a> <!-- NEW -->
</div>
</div>
</div>
</div>
</header>OK then, try the application now, and you should be able to select a blogpost from the home page, which will render the blogpost with an edit button. Selecting edit should then take you to a web form, pre-populated and allow you to make updates. Upon submission, you’ll be redirected back to reading the blogpost.