Flask从html模板接收null

2024-05-06 14:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个网站,接受调查。我正在接受问题及其相关选项并显示它们。它们已成功显示,但我无法访问它们的id以更新其值

我以前尝试过使用flask的方法从多个单选按钮请求选择,但它给了我一个错误的请求

这是我的html页面:

{% extends "layout.html" %}

{% block title %}
    Take Survey
{% endblock %}

{% block main %}


  {% for survey in surveys %}
  <h2 >{{survey.topic}}</h2> <br>

  <form action="/take" method="post" >

    <script>
        function change( val1,val2) {
                        document.getElementById(val1).value = val2
                    }
    </script>
  {% for question in questions %}
        <input type="hidden" name="{{question.id}}" id="{{question.id}}">
      <h3>Q. {{question.question}}</h3> <br><br>

            {% for option in options[question.id] %}

                <input type="radio" onselect="change({{question.id}},{{option.id}})" > {{option.option}}<br>

            {% endfor %}



    {% endfor %}
    <br>
        <input type="hidden" name="survId" value="{{survey.id}}">
        <input type="hidden" name="button" id="bqp">
        <button class="btn btn-primary"  id="continue" type="submit">Continue</button>
        <button class="btn btn-primary"  id ="cancel" type="submit">Cancel</button>
         <script>
        document.getElementById("continue").addEventListener("click", buttonFind);
        document.getElementById("cancel").addEventListener("click", buttonFind);

        function buttonFind() {
            document.getElementById("bqp").value = this.id
        }
    </script>
        <br>
    </form>


    {% endfor %}

{% endblock %}

这是我的路线:

@app.route("/take", methods= ["GET","POST"])
@login_required
def take():

if request.method =="POST":
    survey = request.form.get("survId")
    button = request.form.get("button")

    if button == "cancel" :
        searches=db.execute("SELECT * FROM surveys ORDER BY views DESC")
        return render_template("homepage.html",searches=searches)

    db.execute("UPDATE surveys SET views = views + 1 WHERE id=:surveyid",surveyid=survey)
    questions = db.execute("SELECT id FROM questions WHERE surveyid=:surveyid", surveyid=survey)

    for question in questions:
        choice  = request.form.get(str(question))
        db.execute("UPDATE options SET choicevalue = choicevalue + 1 WHERE option=:option", option=choice)

    searches=db.execute("SELECT * FROM surveys ORDER BY views DESC")
    return render_template("homepage.html",searches=searches)

else:
    return render_template("take.html")

在我看来,我应该从flask接收optionid,但以下SQL查询最终运行,表明我接收到null:

UPDATE surveys SET views = views + 1 WHERE id='41'
DEBUG:cs50:SELECT id FROM questions WHERE surveyid='41'
DEBUG:cs50:UPDATE options SET choicevalue = choicevalue + 1 WHERE option=NULL
DEBUG:cs50:UPDATE options SET choicevalue = choicevalue + 1 WHERE option=NULL

Tags: brformidhtmltypebuttonwhereviews