【问题标题】:Show HTML5 comment list with flask and SQLAlchemy使用烧瓶和 SQLAlchemy 显示 HTML5 评论列表
【发布时间】:2020-11-12 04:16:57
【问题描述】:

我的烧瓶应用程序需要帮助!我想在我的模板reviews.html中显示帖子的cmets列表,但它没有显示cmets,评论路径如下:

@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)

我的reviews.html文件如下:

<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>

我添加我的 model.py 文件,看看它是否与我在数据库中的表有关:

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)

有什么问题我都关注cmets,谢谢!

【问题讨论】:

    标签: python mysql flask-sqlalchemy


    【解决方案1】:

    如下解决我的问题:

    我的 ma​​in.py 文件

    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)
    

    我的 review.html 文件

    <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>
    

    谢谢,希望对你有帮助!

    【讨论】:

      【解决方案2】:

      您必须使用 jinja 模板来循环遍历 cmets。

      你可以这样做:

      <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>
      

      【讨论】:

      • 你能检查我更新的答案吗,用Comment.post_id=num替换Comment.post_id==num
      • 这会引发以下错误:comments_tag = db.session.query (Comment) .filter (Comment.post_id = num) .all () ^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
      • 哦,好吧,我认为您需要查看此查询部分,在 HTML 中我已建议更改。你能通过print(comments_tag)检查python文件中是否有预期的结果吗?
      • 是的,我试了一下,它给了我预期的结果,但它没有显示字符串中的评论,而是显示类似[&lt;Comment 1&gt;, &lt;Comment 2&gt;]
      • 好的,我推荐使用marshmallow。它允许您创建序列化程序来表示您的模型实例,并支持关系和嵌套对象。
      猜你喜欢
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多