0

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!

2 Answers 2

1

Solve my problem as follows:

my main.py file

num = post_id
posts_tag = db.session.query(Post).filter_by(id=num).first()
comment = db.session.query(Comment).filter(Comment.post_id==num).all()
comment_len = len(comment)

my review.html file

<ul class="list-group">
{% for comment in comments %}
  <li class="list-group-item">
    <h5 id="user-comment">{{ comment.text }}</h5>
    <h6>{{ comment.user_id }}</h6>
    <h6>{{ comment.created_date }}</h6>
   </li>
{% endfor %}
</ul>

Thank you, I hope it helps you!

Sign up to request clarification or add additional context in comments.

Comments

0

You have to use jinja templating for looping through the comments.

You can do like this:

<ul class="list-group">
{% for comment in comments %}
  <li class="list-group-item">
    <h5 id="user-comment">{{ comment.username }}</h5> 
    <p id="comment-text">{{ comment.text }}</p>
    <footer>{{ comment.created_date }}</footer>
  </li>
{% endfor %}
</ul>

7 Comments

Can you check my updated answer, replace Comment.post_id==num with Comment.post_id=num
that throws me the following error: comments_tag = db.session.query (Comment) .filter (Comment.post_id = num) .all () ^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
oh okay, I think you need to look at this query part, in HTML I have suggested the changes. Can you check by print(comments_tag) if there are expected results or not in python file?
yes, I try that, it gives me the expected results, but it doesn't show me the comment in string, instead it shows me something like [<Comment 1>, <Comment 2>]
okay, I recommend using marshmallow. It allows you to create serializers to represent your model instances with support to relations and nested objects.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.