Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用户只能投票一次,如何投票?_Python_Flask_Flask Sqlalchemy_Vote - Fatal编程技术网

Python 用户只能投票一次,如何投票?

Python 用户只能投票一次,如何投票?,python,flask,flask-sqlalchemy,vote,Python,Flask,Flask Sqlalchemy,Vote,我创建了一个Flask博客,你可以从1-5对博客帖子进行评分。现在,每个用户都可以多次投票。我希望他们只能投票一次。在routes.py文件中,我编写了以下代码: def rating(recipe_id): current_recipe = Recipe.query.get_or_404(recipe_id) form = RatingForm() if form.validate_on_submit(): if current_user.is_auth

我创建了一个Flask博客,你可以从1-5对博客帖子进行评分。现在,每个用户都可以多次投票。我希望他们只能投票一次。在routes.py文件中,我编写了以下代码:

def rating(recipe_id):
    current_recipe = Recipe.query.get_or_404(recipe_id)
    form = RatingForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            new_rating = Rating(rating=form.rating.data,
                                user=current_user,
                                recipe=current_recipe)
            db.session.add(new_rating)
            try:
                db.session.commit()
                form.rating.data = ""
                flash('You have voted!', 'success')
            except Exception as e:
                db.session.rollback()
                app.logger.critical(f'Error while voting: {new_rating}')
                app.logger.exception(e)
                flash('There was an error when voting. Try again later.', 'danger')
        else:
            flash('You are not logged in. You need to be logged in to be able to rate a recipe!', 'danger')
    return render_template('recipe_page.html',
                           title=current_recipe.title,
                           post=current_recipe,
                           form=form
                           )
我的HTML中还有:

<form method="POST" action="">
  {% for option in form.rating %}
         <div class = "form-check">
            {{ option(class="form-check-input") }}
            {{ option.label(class="form-check-label") }}
         </div>
  {% endfor %}

    <div class="form-group">
      {{ form.csrf_token }}
      {{ form.submit(class="btn btn-outline-info") }}
    </div>

{form.rating%%中的选项为%1}
{{option(class=“form check input”)}
{{option.label(class=“form check label”)}
{%endfor%}
{{form.csrf_token}
{{form.submit(class=“btn btn outline info”)}

我怎么能写一个代码让每个人只能投票一次?提前感谢:)

检查一下用户是否提前投票,如果投票了就不要让他们投票,否则就允许他们投票是的,但我不知道如何编写这样的代码…:(在
评级
数据库模型中似乎有名为
用户
配方
的字段,请检查
评级
表中是否已经有来自当前配方的当前用户所在数据库的记录。如果该记录不存在,则可以将其添加到数据库中,否则不要添加到数据库中保留用户问题的投票记录,因此当用户登录到该问题时,调用后端以检查用户是否有投票计数,如果有,则将该数据存储在js对象中,现在当用户单击vote+时,您检查该数据对象,查看用户是否已投票,如果已投票,则向他显示错误,否则,s将该响应保存在数据库中,让用户投票