Search code examples
pythonweb-applicationsflasksqlalchemyflask-wtforms

How to add comments feature to posts in a flask web application


I am developing a web application with Flask.I am confused how to add comment feature to posts in a web application. Parts of my database models are a give below

class Post(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(140))
    body = db.Column(db.String(2000))
    timestamp = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    comments = db.relationship('Comment', backref='title', lazy='dynamic')

    def get_comments(self):
        return Comment.query.filter_by(post_id=post.id).order_by(Comment.timestamp.desc())


    def __repr__(self):
        return '<Post %r>' % (self.body)

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'))

    def __repr__(self):
        return '<Post %r>' % (self.body)

And post and comment forms as

class PostForm(Form):
    post = StringField('post', validators=[DataRequired()])
    title = StringField('title', validators=[DataRequired()])
class CommentForm(Form):
    comment = StringField('post', validators=[DataRequired()])

The posts are returned by a function blog_posts() in 'User' model

def blog_posts(self):
        return Post.query.order_by(Post.timestamp.desc())

Not sure how to return the comments corresponding to each post. After getting posts my code calls render template(index.html). Then how can I obtain comments and print them?. Please help I am a beginner python developer


Solution

  • Since you've defined the relationship between Post and Comment, you can simply do something like the following in your template:

                    {% if post.comments %}
                    {% if post.comments.count() > 0 %}
                        <h2>Comments</h2>
                        <p>
                        {% for comment in post.comments %}
                            <p>{{ comment.body }}</p>
                        {% endfor %}
                        </p>
                    {% endif %}
                    {% endif %}