【问题标题】:Allow only one comment in flask在烧瓶中只允许一条评论
【发布时间】:2025-12-26 12:55:17
【问题描述】:

我在烧瓶 API 中有一个 Web 应用程序,用户可以在其中留下 cmets 和星级评分 (1-5)。我会将这些评分用于电影推荐算法。我想允许一个用户对每部电影发表一条评论,但我不想让他们留下一条以上的评论。如果他们有评论,我希望他们编辑该评论。

我的评论表:

id content rating commenter_id movie_id
1 Wery good movie 5 1 1
2 I like this movie 5 1 1

所以基本上我不想让在这种情况下 id=2 发生的事情

@app.route("/movie/<int:movie_id>", methods=['GET', 'POST'])
@login_required
def movie(movie_id):
    movie = Movie.query.get_or_404(movie_id)
    comments = Comment.query.filter_by(movie_id=movie_id).all()
    current_user_comments = Comment.query.filter_by(movie_id=movie_id,commenter_id=current_user.id).first()
    if current_user_comments:
        print('Has')
    else:
        print('Has not')
    form = CommentForm()
    if form.validate_on_submit():
        comment= Comment(content=form.content.data, rating=request.form.get("rating"), commenter_id=current_user.id, movie_id=movie_id)
        db.session.add(comment)
        db.session.commit()
        flash('Comment has been added!', 'success')
        return redirect(request.url)
    return render_template('movie.html', title=movie.title, movie=movie,comments=comments,form=form)

如果用户对特定电影有评论,我打印“有”,如果他没有,我打印“没有”。现在我必须弄清楚如何让他编辑已经存在的评论而不是创建新评论。

【问题讨论】:

    标签: python mysql flask web frontend


    【解决方案1】:

    您在print()“有”的地方使用语法创建CommentForm

    form = CommentForm(obj=curren_user_cmets)

    在 else 分支中

    form = CommentForm()

    这将向用户显示他之前的评论,如果他有之前的 cmets,则可以更改 cmets,否则他将看到一个页面以添加新评论。

    在更新中,您也需要更改代码。如果你有现有的current_user_comments,你想更新它,当然不要创建一个新的。您可能希望限制用户可以更新的字段,例如实际的 cmets 文本和评级。

    【讨论】: