python - 在帖子下显示评论的聪明方法是什么?
问题描述
我目前可以写我的帖子和对我的数据库的回复,但现在我被困在如何显示我对我的特定帖子的回复以及如何显示帖子下的评论。任何提示都有助于特别是指向有关此类问题的正确文档的指针。
路线.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 %}
解决方案
- 定义一个名为 comments 的表
- 将关系帖子评论定义为一对多,并带有适当的反向引用
- 在每个帖子下做:
{%for comment in post.comments%}
{%endfor%}
推荐阅读
- java - Java中线程失败的常见原因有哪些
- html - 将文本包裹在图像 CSS 上
- mysql - 通过 ODBC 在 SSRS 报告中调用带有参数的 MySQL 存储过程
- regex - 正则表达式确保四个字母之一只出现一次
- php - Artisan serve all functions 完美运行,但是当我在 Xampp 上运行它时,某些功能不起作用
- qt - 如何防止系列值缩放到 Qt 图表轴的 100% 范围?
- javascript - onChange 在 reactjs antd 中使用 setState 时返回一个回调
- apache - 如何用问号重定向链接
- android - 在后台Android中进行繁重处理时UI冻结
- reactjs - 使用来自反应应用程序的 axios 将数据传递给 Web 服务