简体   繁体   English

flask 中只允许一条评论

[英]Allow only one comment in flask

I have a web application in a flask API where users leave comments and star ratings(1-5).我在 flask API 中有一个 web 应用程序,用户在其中留下评论和星级评分(1-5)。 I will use those ratings for a movie recommender algorithm.我会将这些评分用于电影推荐算法。 I want to allow for one user to leave one comment to each movie, but I don't want for them to leave more than one comment.我想允许一个用户对每部电影发表一条评论,但我不想让他们留下一条以上的评论。 If they have a comment I want for them to edit that comment.如果他们有评论,我希望他们编辑该评论。

My comment table:我的评论表:

id ID content内容 rating评分 commenter_id评论者 ID movie_id电影编号
1 1 Wery good movie很好的电影 5 5 1 1 1 1
2 2 I like this movie我喜欢这部电影 5 5 1 1 1 1

So basically I don't want to allow what is happening where in this case id=2所以基本上我不想让在这种情况下发生的事情 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)

If user has comment on spesific movie I print 'Has' if he has not I print 'Has not'.如果用户对特定电影有评论,我会打印“有”,如果他没有,我会打印“没有”。 Now I have to figure out how to make him edit already existing comment instead of creating new.现在我必须弄清楚如何让他编辑已经存在的评论而不是创建新评论。

Where you print() "Has" you create the CommentForm using the syntax你在哪里print() "Has" 你使用语法创建CommentForm

form = CommentForm(obj=curren_user_comments) form = CommentForm(obj=curren_user_comments)

and in the else branch在 else 分支中

form = CommentForm()表格 = 评论表格()

This will present the user with his earlier comment and enable changing the comments if he has previous comments, else he will be presented with a page to add a new comment.这将向用户显示他之前的评论,如果他有之前的评论,则可以更改评论,否则他将看到一个页面以添加新评论。

In the update you will want to change the code too.在更新中,您也需要更改代码。 In case you have existing current_user_comments you want to update this, not create a new one of course.如果你有现有的current_user_comments你想更新它,当然不要创建一个新的。 You may want to limit the fields the user can update to eg the actual comments text and the rating.您可能希望将用户可以更新的字段限制为例如实际评论文本和评级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM