Chapter 13. User Comments

Allowing users to interact is key to the success of a social blogging platform. In this chapter, you will learn how to implement user comments. The techniques presented are generic enough to be directly applicable to a large number of socially enabled applications.

Database Representation of Comments

Comments are not very different from blog posts. Both have a body, an author, and a timestamp, and in this particular implementation both are written with Markdown syntax. Figure 13-1 shows a diagram of the comments table and its relationships with other tables in the database.

Database representation of blog post comments.
Figure 13-1. Database representation of blog post comments

Comments apply specific blog posts, so a one-to-many relationship from the posts table is defined. This relationship can be used to obtain the list of comments associated with a particular blog post.

The comments table is also in a one-to-many relationship with the users table. This relationship gives access to all the comments made by a user, and indirectly how many comments a user has written, a piece of information that can be interesting to show in user profile pages. The definition of the Comment model is shown in Example 13-1.

Example 13-1. app/models.py: Comment model
class Comment(db.Model):
    __tablename__ = 'comments'
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    body_html = db.Column(db.Text)
    timestamp ...

Get Flask Web Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.