I need help with my flask app!. I want to show a list of comments for posts in my template reviews.html, but it does not show me the comments, the reviews path is as follows:
@app.route('/reviews/<int:post_id>', methods=['GET', 'POST'])
def reviews(post_id = Post.id):
comment_form = forms.CommentForm(request.form)
if request.method == 'POST' and comment_form.validate():
user_id = session['user_id']
comment = Comment(user_id = user_id,
post_id = post_id,
text = comment_form.comment.data)
db.session.add(comment)
db.session.commit()
success_message = 'Comentario agregado!'
flash(success_message)
num = post_id
posts_tag = db.session.query(Post).filter_by(id=num).first()
comments_tag = db.session.query(Comment).filter(Comment.post_id==num).all()
comment_count = Comment.query.count()
return render_template('reviews.html',
post = posts_tag,
form = comment_form,
comments = comments_tag,
date_format = date_format,
comment_count = comment_count)
My reviews.html file is as follows:
<button type="button" class="collapsible">
<h5>Comentarios ({{ comment_count }})</h5>
</button>
<ul class="list-group">
<li class="list-group-item">
<h5 id="user-comment">{{ comments.username }}</h5>
<p id="comment-text">{{ comments.text }}</p>
<footer>{{ comments.created_date }}</footer>
</li>
</ul>
I add my model.py file to see if it has something to do with my table in the database:
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from sqlalchemy import MetaData
import datetime
db = SQLAlchemy()
bcrypt = Bcrypt()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True)
email = db.Column(db.String(40))
password = db.Column(db.String(66))
comments = db.relationship('Comment')
posts = db.relationship('Post')
create_date = db.Column(db.DateTime, default=datetime.datetime.now)
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = self.__create_pasword(password)
def __create_pasword(self, password):
return bcrypt.generate_password_hash(password).decode ('utf-8')
def verify_password(self, password):
return bcrypt.check_password_hash(self.password, password)
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
title = db.Column(db.String(50))
comment_id = db.relationship('Comment')
text = db.Column(db.Text())
created_date = db.Column(db.DateTime, default=datetime.datetime.now)
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
text = db.Column(db.Text())
created_date = db.Column(db.DateTime, default=datetime.datetime.now)
Any questions I am attentive to the comments, thanks!