Comments Functionality
NotesAdding comment functionality builds further on the concepts of database relationships. For example:
- Users need to be logged in to leave comments.
- A comment will be owned by a user.
- A comment needs to be approved by a site administrator.
- A user can have made many comments.
- Only the owner of a comment should be able to delete it.
- Each comment belongs to one blog post.
- A blog post can have many comments by different users.
There is a lot to consider here, hence why projects can become exponentially complex as they evolve.
That said, by breaking this down, updating the database schemas, and adding the CRUD functionality for comments, we can tackle all the bullet points.
You can visualise these relationships, for example each comment will belong to a user and a blogpost:
Each user could have many comments, and each blogpost can have many comments:
Schemas#
The first step is to add the schemas for comments, at the top of blog_schemas.py:
# Comment Schemas
class CommentIn(SQLModel):
comment: str = Field(min_length=1, max_length=2000)
class CommentOut(CommentIn):
id: uuid.UUID
approved: bool
created_date: datetime.datetime
comment_author_id: uuid.UUID | NoneAnd the table model, at the bottom:
class Comment(CommentIn, table=True):
id: uuid.UUID = Field(
default_factory=uuid.uuid4,
primary_key=True)
created_date: datetime.datetime = Field(
default_factory=lambda: datetime.datetime.now(datetime.UTC))
approved: bool = False
blogpost_id: uuid.UUID = Field(foreign_key="blogpost.id", ondelete="CASCADE")
blogpost: BlogPost = Relationship(back_populates="comments")
comment_author_id: uuid.UUID | None = Field(default=None, foreign_key="user.id")
comment_author: "User" = Relationship(back_populates="comments")Every comment must belong to a blog post, while its author is optional, so a comment can survive if its author’s account is deleted. New comments aren’t approved, so they’re hidden until an administrator approves them (in the Site Admin section).
We need to update both the BlogPost and User schemas with the corresponding back_populates relationship. For blog posts:
class BlogPostOut(BlogPostIn):
id: uuid.UUID
created_date: datetime.datetime
blogpost_author_id: uuid.UUID | None
comments: list[CommentOut] = [] # NEW
# SQLModel Database Schemas
class BlogPost(BlogPostIn, table=True):
id: uuid.UUID = Field(
default_factory=uuid.uuid4,
primary_key=True)
created_date: datetime.datetime = Field(
default_factory=lambda: datetime.datetime.now(datetime.UTC))
blogpost_author_id: uuid.UUID | None = Field(default=None, foreign_key="user.id")
blogpost_author: "User" = Relationship(back_populates="blogposts")
comments: list["Comment"] = Relationship(back_populates="blogpost", cascade_delete=True) # NEWcascade_delete=True means deleting a blog post deletes its comments too. Without it, deleting a post with comments would leave comments pointing at a post that no longer exists, which PostgreSQL refuses. ondelete="CASCADE" on the foreign key tells the database to do the same, in case rows are ever deleted outside the application. "Comment" is a string because the Comment class is defined further down the file.
For the user, import Comment and CommentOut and add:
from db.schemas.blog_schemas import BlogPost, BlogPostOut, Comment, CommentOut # UPDATEDclass UserOut(SQLModel):
# ... the existing fields ...
blogposts: list[BlogPostOut] = []
comments: list[CommentOut] = [] # NEWclass User(SQLModel, table=True):
# ... the existing fields ...
blogposts: list[BlogPost] = Relationship(back_populates="blogpost_author")
comments: list[Comment] = Relationship(back_populates="comment_author") # NEWLet Alembic know about the new table:
from db.schemas.blog_schemas import BlogPost, Comment # UPDATEDAnd create the migration (in the example code, together with the authors from the previous section):
alembic revision --autogenerate -m "added post authors and comments"def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('comment',
sa.Column('comment', sqlmodel.sql.sqltypes.AutoString(length=2000), nullable=False),
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('created_date', sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False),
sa.Column('approved', sa.Boolean(), nullable=False),
sa.Column('blogpost_id', sa.Uuid(), nullable=False),
sa.Column('comment_author_id', sa.Uuid(), nullable=True),
sa.ForeignKeyConstraint(['blogpost_id'], ['blogpost.id'], name=op.f('fk_comment_blogpost_id_blogpost'), ondelete='CASCADE'),
sa.ForeignKeyConstraint(['comment_author_id'], ['user.id'], name=op.f('fk_comment_comment_author_id_user')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_comment'))
)
with op.batch_alter_table('blogpost', schema=None) as batch_op:
batch_op.add_column(sa.Column('blogpost_author_id', sa.Uuid(), nullable=True))
batch_op.create_foreign_key(batch_op.f('fk_blogpost_blogpost_author_id_user'), 'user', ['blogpost_author_id'], ['id'])
# ### end Alembic commands ###alembic upgrade headAPIs#
Next, add the API functions for comments to blog_apis.py. You’ll need to import the comment schemas:
from db.schemas.blog_schemas import BlogPostIn, BlogPostOut, BlogPost, CommentIn, CommentOut, Comment # UPDATED# Comments
@router.post('/blog/{blogpost_id}/comment', status_code=status.HTTP_201_CREATED)
def add_comment_api(blogpost_id: uuid.UUID, user_id: uuid.UUID, comment_input: CommentIn,
session: Session = Depends(get_session_db)) -> CommentOut:
if not session.get(BlogPost, blogpost_id):
raise HTTPException(status_code=404, detail=f"No blog post found with id {blogpost_id}.")
new_comment = Comment.model_validate(comment_input, update={"blogpost_id": blogpost_id,
"comment_author_id": user_id})
session.add(new_comment)
session.commit()
session.refresh(new_comment)
return new_comment
@router.get('/blog/{blogpost_id}/comments', status_code=status.HTTP_200_OK)
def get_comments_by_blogpost_id_api(blogpost_id: uuid.UUID, approved_only: bool = True,
session: Session = Depends(get_session_db)) -> list[CommentOut]:
query = select(Comment).where(Comment.blogpost_id == blogpost_id)
if approved_only:
query = query.where(Comment.approved == True)
return session.exec(query.order_by(Comment.created_date.desc())).all()
@router.delete('/blog/comment/{comment_id}', status_code=status.HTTP_204_NO_CONTENT)
def delete_comment_by_id_api(comment_id: uuid.UUID, comment_author_id: uuid.UUID,
session: Session = Depends(get_session_db)) -> None:
comment = session.get(Comment, comment_id)
if not comment or comment.comment_author_id != comment_author_id:
raise HTTPException(status_code=404,
detail=f"No comment found with id {comment_id}, or it isn't yours to delete.")
session.delete(comment)
session.commit()add_comment_apichecks the blog post exists, then creates the comment for it and its author.get_comments_by_blogpost_id_apireturns a post’s comments, newest first, only the approved ones unless asked otherwise.delete_comment_by_id_apionly deletes a comment ifcomment_author_idmatches its author, and otherwise responds with404, which doesn’t reveal whether the comment exists.
All three paths are longer than /blog/{id}, so they don’t clash with it. An earlier version of this guide had a GET /blog/comments route after GET /blog/{id}, which could never be reached: /blog/{id} matched first and rejected comments as an invalid UUID.
To try these APIs you will need valid UUIDs for a user and a blogpost, which you can find with the existing APIs. Once you’ve added some test comments, the API for returning a blogpost by id includes its comments, and the user API includes theirs:
{
"title": "At vero eos",
"...": "...",
"id": "76ef90d6-7981-4c3e-8c49-73b1e9d225f9",
"blogpost_author_id": "cebb000b-e9d9-4c71-91a6-ef2b3dabd5fa",
"comments": [
{
"comment": "Hello World!",
"id": "ab236663-d6f9-400a-a8cc-5a904ab11a84",
"approved": false,
"created_date": "2026-12-02T09:31:53.866010Z",
"comment_author_id": "b68e6992-5899-49c0-bf8c-3292a02eeb79"
}
]
}Comments on the blog post page#
Update the blogpost_get_view to include the approved comments, and add two views: one to add a comment, and one to delete one:
@router.get('/blog/{id}', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_get_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
post = get_blogpost_by_id_api(id=id, session=session)
comments = get_comments_by_blogpost_id_api(blogpost_id=id, session=session)
blogpost_owner = current_user is not None and post.blogpost_author_id == current_user.id
markdown_content = nh3.clean(markdown.markdown(post.content))
context = {
"page": "blog",
"post": post,
"markdown": markdown_content,
"blogpost_readtime": read_time_minutes(post.content),
"user": current_user,
"blogpost_owner": blogpost_owner,
"comments": comments,
}
return templates.TemplateResponse(request, 'blogpost.html', {'context': context})
@router.post('/blog/{id}/comment', response_class=HTMLResponse)
def comment_create_post_view(*,
id: uuid.UUID,
request: Request,
comment: str = Form(...),
session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
add_comment_api(blogpost_id=id, user_id=current_user.id, comment_input=CommentIn(comment=comment), session=session)
return RedirectResponse(f'/blog/{id}', status_code=status.HTTP_303_SEE_OTHER)
@router.post('/blog/{id}/comment/{comment_id}/delete', response_class=HTMLResponse)
def comment_delete_post_view(*,
id: uuid.UUID,
comment_id: uuid.UUID,
request: Request,
session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
delete_comment_by_id_api(comment_id=comment_id, comment_author_id=current_user.id, session=session)
return RedirectResponse(f'/blog/{id}', status_code=status.HTTP_303_SEE_OTHER)The important detail in both new views is where the user comes from. They take the logged-in user from the login cookie, with is_user(), and never from the submitted form.
An earlier version of this guide put the user’s id in a hidden form field, and the views used it, without checking anyone was logged in. Anyone could change that hidden value (it’s just HTML) and post comments as any user, or delete anyone’s comments. The browser is under the user’s control: anything it sends, including hidden fields, cookies you didn’t sign and URLs, can be changed. Identity must come from something the server can verify, which here is the signed JWT in the cookie.
The blog post and comment ids are in the URLs, like the other blog views, so the forms don’t need hidden fields at all.
Then add the comments, the comment form, and a delete button for the user’s own comments to blogpost.html, after the post content:
<hr>
<h4>Comments</h4>
{% for comment in context.comments %}
<article>
<p><i>{{ comment.comment }}</i></p>
<h6>Commented on {{ comment.created_date.strftime('%d %B %Y') }}{% if comment.comment_author %}
by {{ comment.comment_author.first_name }} {{ comment.comment_author.last_name }}{% endif %}</h6>
{% if context.user and comment.comment_author_id == context.user.id %}
<form action="/blog/{{ context.post.id }}/comment/{{ comment.id }}/delete" method="post"
onsubmit="return confirm('Are you sure?')">
<button type="submit" class="btn-sm btn-danger">Delete</button>
</form>
{% endif %}
</article>
{% else %}
<p>No comments yet.</p>
{% endfor %}
{% if context.user %}
<hr>
<p><strong>Leave a comment:</strong></p>
<form action="/blog/{{ context.post.id }}/comment" method="post">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Comment</label>
<textarea class="form-control" placeholder="Comment" id="comment" name="comment"
rows="3" maxlength="2000" required></textarea>
</div>
</div>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<p><small>Comments appear once they've been approved.</small></p>
{% else %}
<p><a href="/auth/login">Log in</a> to leave a comment.</p>
{% endif %}{% for ... %}{% else %}{% endfor %} is a handy Jinja feature: the else part is shown when the list is empty.
While developing, you can approve comments in the database, for example with sqlite3: UPDATE comment SET approved = 1;. The Site Admin section adds pages for it.
Users can now comment, see their comments once approved, and delete their own comments, but not other users’ comments.
Testing#
The example code includes test_authorisation.py, which checks that new posts record their author, that other authors can’t edit or delete them (even by sending the forms directly), that commenting needs a login, that comments only appear once approved, that only a comment’s author can delete it, and that deleting a post deletes its comments.
The example code at this point is tagged ch07-authorisation in the example repository. To get it:
git clone https://github.com/codewalkr/fastapi-example-for-you.git
cd fastapi-example-for-you
git checkout ch07-authorisation