【问题标题】:What is the smart way to display comments under posts?在帖子下显示评论的聪明方法是什么?
【发布时间】:2020-12-27 05:51:13
【问题描述】:

我目前可以写我的帖子和对我的数据库的回复,但现在我被困在如何显示我对我的特定帖子的回复以及如何显示帖子下有 cmets 的帖子。任何提示都有助于特别指出有关此类问题的正确文档。

routes.py

@app.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data, content=form.content.data, author=current_user,)
        db.session.add(post)
        db.session.commit()
        flash('New Post Created', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html', title='New Post', form=form, legend='New Post')


@app.route("/post/<int:post_id>")
def post(post_id):
    post = Post.query.get_or_404(post_id)
    return render_template('post.html', title=post.title, post=post,)


@app.route("/post/reply", methods=['GET', 'POST'])
@login_required
def new_reply():
    form = ReplyForm()
    if form.validate_on_submit():
        reply = Reply(title=form.title.data, content=form.content.data, author=current_user,)
        db.session.add(reply)
        db.session.commit()
        flash('reply posted', 'success')
        return redirect(url_for('home'))
    return render_template('Reply.html', title='New Reply', form=form, legend='New Reply')

post.html

{% block content %}
  <article class="media content-section">
    <img class="article-img" src="{{ url_for('static', filename='profile_pics/' + post.author.image_file) }}">
    <div class="media-body">
      <div class="article-metadata">
        <a class="mr-2" href="{{ url_for('user_posts', username=post.author.username) }}">{{ post.author.username }}</a>
        <small class="text-muted">{{ post.date_posted}}</small>
        {% if post.author == current_user %}
          <div>
            <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{{ url_for('update_post', post_id=post.id) }}">[ Update ]</a>
            <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{{ url_for('new_reply', post_id=post.id) }}">[ Reply ]</a>
            <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{{ url_for('delete_post', post_id=post.id) }}">[ Delete ]</a>
          </div>
        {% else %}
        {% if current_user.is_authenticated %}
        <div>
        <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{{ url_for('new_reply', post_id=post.id ) }}">[ Reply ]</a>
        </div>
        {% endif %}
        {% endif %}
      </div>
      <h2 class="article-title">{{ post.title }}</h2>
      <p class="article-content">{{ post.content }}</p>
    </div>
  </article>
{% endblock content %}

【问题讨论】:

  • 你遇到了什么问题?
  • 在“post”中加载帖子时,还要加载 cmets,其中帖子数据库中的外键与帖子的主键匹配。然后组装模板。非常基本的东西......

标签: python flask sqlalchemy flask-wtforms


【解决方案1】:

如果您修改模型以多对一关系连接 cmets 和帖子,则可以实现此目的。 (很多cmet都和一个帖子有关)


from app         import db
from flask_login import UserMixin
from datetime    import datetime

class User(UserMixin, db.Model):
    id       = db.Column(db.Integer,     primary_key=True)
    username = db.Column(db.String(64),  unique = True)
    email    = db.Column(db.String(120), unique = True)
    password = db.Column(db.String(500))

class Post(db.Model):
    id          = db.Column(db.Integer, primary_key=True)
    title       = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content     = db.Column(db.Text, nullable=False)
    user_id     = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

class Reply(db.Model):
    id          = db.Column(db.Integer, primary_key=True)
    post_id     = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
    user_id     = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    content     = db.Column(db.Text, nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    

现在您可以通过使用post_id 简单地查询回复表来获取帖子的所有回复

from .models import Reply

replies = Reply.query.filter_by(post_id=`your_post_id_here').all()

您可以获取 replies 列表并将其呈现在模板中

【讨论】:

    【解决方案2】:
    • 定义一个名为 cmets 的表
    • 将关系 post-cmets 定义为一对多,并带有适当的反向引用
    • 在每个帖子下做:
    {%for comment in post.comments%}
    
    {%endfor%}
    

    【讨论】:

    • 当您说“将关系帖子-cmets 定义为一对多”时,您是什么意思?我已经有一个名为“reply”的数据库表,我记得 2015 年有一篇关于我有类似的问题,但我找不到。
    • 例如this file Category 与 SubCategory 是一对多的关系。看看它是如何使用 flask-sqlalchemy 完成的
    猜你喜欢
    • 2017-02-11
    • 2018-10-21
    • 2019-08-24
    • 2019-12-07
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 2015-05-24
    • 2022-01-10
    相关资源
    最近更新 更多