首页 > 解决方案 > 在帖子下显示评论的聪明方法是什么?

问题描述

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

路线.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 %}

标签: pythonflasksqlalchemyflask-wtforms

解决方案


  • 定义一个名为 comments 的表
  • 将关系帖子评论定义为一对多,并带有适当的反向引用
  • 在每个帖子下做:
{%for comment in post.comments%}

{%endfor%}

推荐阅读