如何使用烧瓶形式获取RadioField的值?

时间:2019-04-17 23:45:27

标签: python database flask sqlalchemy

我无法使用烧瓶形式获取烧瓶SQLalchemy中单选按钮的值。

class AnswerForm(Form):
    ans = 'ddd'
    your_answer = RadioField("", choices=[('ans1', 'ans1'),('ans2','q.ans2'), ('ans3','q.ans3'), ('ans4','q.ans4')])
    submit = SubmitField('Answer')

路线:

@app.route('/question', methods=['GET', 'POST'])
@app.route('/question/page/<int:page>', methods=['GET', 'POST'])
def question(page=1):
    # questions = Question.query.paginate(page, per_page=1)
    quess = Question.query.order_by(func.rand())
    quest = quess.limit(3).from_self()
    questions = quest.paginate(page, per_page=1)
    print('new1')

    form = AnswerForm()

    if request.method == 'POST':

        print "submitted"
        print form.ans
        print form.your_answer.data
    return render_template('questionview.html', title=' Quiz', questions=questions, form=form)

HTML:这是我的代码。它使用Flask SQL炼金术从数据库中获取问题和选项。 ................................................... ..........................

<form method="POST" action="">
  <div class="jumbotron text-center">
 <h1>Start a test</h1>

    {% for q in questions.items %}

    <ul class="list-group">

      <li class="list-group-item" name='que_desc'><a href="subject_test/{{q.sub_id}}">{{q.ques}}</a></li>
      <div class="form-check">
        <input class="form-check-input" type="radio" name="option" id="exampleRadios1" value="ans1">
        <label class="form-check-label" for="exampleRadios1">
          {{q.ans1}}
        </label>
      </div>
      <br>
      <div class="form-check">
        <input class="form-check-input" type="radio" name="option" id="exampleRadios2" value="ans2">
        <label class="form-check-label" for="exampleRadios2">
          {{q.ans2}}
        </label>
      </div>
      <br>
      <div class="form-check">
        <input class="form-check-input" type="radio" name="option" id="exampleRadios2" value="ans3">
        <label class="form-check-label" for="exampleRadios2">
          {{q.ans3}}
        </label>
      </div>
      <br>
      <div class="form-check">
        <input class="form-check-input" type="radio" name="option" id="exampleRadios2" value="ans4">
        <label class="form-check-label" for="exampleRadios2">
          {{q.ans4}}
        </label>
      </div>
      <br>
    </ul>

    <hr>
    {% endfor %}
    {{ form.submit(class="btn btn-outline-info") }}
  </div>
</form>

1 个答案:

答案 0 :(得分:1)

您的表单需要从请求中获取数据。替换:

form = AnswerForm()

使用:

form = AnswerForm(request.form)

有关详细信息:http://flask.pocoo.org/docs/1.0/patterns/wtforms/