【问题标题】:Submitting a HTML form in Flask creates error with request.form在 Flask 中提交 HTML 表单会导致 request.form 出错
【发布时间】:2020-02-03 03:40:51
【问题描述】:

嘿,我是 Flask 的新手,正在尝试制作一个基本的测验应用程序,

@app.route('/answers', methods=['GET', 'POST'])
def answers():
    correct = 0
    incorrect = 0
    total = correct + incorrect
    if request.method == 'POST':
        submitted_answer = request.form['answer']
        if submitted_answer == question_option1:
            correct += 1
            new_result = Question(correct=correct, total=total)
            db.session.add(new_result)
            db.session.commit()
        else:
            incorrect += 1
            new_result = Question(incorrect=incorrect, total=total)
            db.session.add(new_result)
            db.session.commit()
        return redirect('/answers')
    all_questions = Question.query.order_by().all()
    return render_template('answers.html', questions=all_questions, correct=correct, incorrect=incorrect, total=total)

虽然 html 代码看起来像这样

{% extends 'base.html' %}
{% block body %}
   <p1>
    <list>
       {% for question in questions %}
        <h2>{{ question.text }}</h2>
            <input type="radio" name="answer" value="option1"> {{ question.option1 }} <br>
            <input type="radio" name="answer" value="option2"> {{ question.option2 }} <br>
            <input type="radio" name="answer" value="option3"> {{ question.option3 }} <br>
            <input type="radio" name="answer" value="option4"> {{ question.option4 }} <br>

        {%  endfor %}

    </list>
       <form action='/answers' method='POST'>
           <input type="submit" name="submitted" value="Check Scores">


       </form>
   <p1>You got a score of {{ correct }}/{{ total }}</p1>
   </p1>

{% endblock %}

在我的应用程序的不同部分,我可以使用相同的方法从 HTML 获取信息,但在这种情况下,我不断收到错误

'werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: 浏览器(或代理)发送了一个服务器无法理解的请求。 KeyError:'答案''

当我尝试提交清单但无法找出原因时

我是编程新手,如果我遗漏了一些非常基本的东西,非常抱歉,但感谢您的帮助!

【问题讨论】:

    标签: python-3.x flask flask-sqlalchemy


    【解决方案1】:

    您的答案输入需要在要提交的表单标签内 - 您提交的表单中没有“答案”元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 2021-06-10
      相关资源
      最近更新 更多