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


i developing web application flask.i confused how add comment feature posts in web application. parts of database models 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 , comment forms

class postform(form):     post = stringfield('post', validators=[datarequired()])     title = stringfield('title', validators=[datarequired()]) class commentform(form):     comment = stringfield('post', validators=[datarequired()]) 

the posts returned function blog_posts() in 'user' model

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

not sure how return comments corresponding each post. after getting posts code calls render template(index.html). how can obtain comments , print them?. please beginner python developer

since you've defined relationship between post , comment, can following in template:

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

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -