Flask-WTForms form.validate()在动态选择上失败

时间:2018-02-22 20:44:51

标签: python flask wtforms flask-wtforms

我正在创建一个调查应用程序,显示调查问题和选项,并允许用户通过Flask-WTForms包选择一个选项。表单使用RadioField,并且在动态填充choices属性时似乎失败form.validate()

当我手动输入选项时:

class SurveyAnswerForm(FlaskForm):
    answers = RadioField('Answers',
                         coerce=str,
                         choices=[('18-25', '18-25'), ('26-35', '26-35')])

form.validate()返回 True form.error中没有错误。

当我决定动态填充选项属性时(见下文),form.validate()会返回错误form.error会返回:

  

{'答案':['不是有效的选择']}。

我已经在这工作了好几个小时,我不确定为什么form.validate()会返回错误

forms.py

from flask_wtf import FlaskForm
from wtforms import RadioField

class SurveyAnswerForm(FlaskForm):
    answers = RadioField('Answers',
                         coerce=str,
                         choices=[])

app.py

@app.route('/survey/<int:survey_id>/questions', methods=['GET', 'POST'])
def survey_questions(survey_id):
    survey = Survey.query.filter_by(id=survey_id).first()
    page = request.args.get('page', 1, type=int)
    questions = SurveyQuestion.query.filter_by(survey_id=survey_id)\
        .order_by(SurveyQuestion.id)\
        .paginate(page, 1, True)

    for question in questions.items:
        question_id = question.id

    choices = QuestionChoices.query\
        .join(SurveyQuestion,
              and_(QuestionChoices.question_id==question_id,
               SurveyQuestion.survey_id==survey_id)).all()

    form = SurveyAnswerForm(request.form)
    form.answers.choices = [(choice.choice, choice.choice)\
        for choice in choices]

    if request.method =='POST' and form.validate():
        print('Successful POST')

    next_url = url_for('survey_questions', survey_id=survey.id,
                       page=questions.next_num)\
        if questions.has_next else None
    prev_url = url_for('survey_questions', survey_id=survey.id,
                   page=questions.prev_num)\
        if questions.has_prev else None

    return render_template('survey_question.html',
                           survey=survey,
                           questions=questions.items,
                           choices=choices,
                           form=form,
                           next_url=next_url, prev_url=prev_url)

survey_question.html

{% extends "layout.html" %}
{% block body %}
  <h2>{{ survey.survey_title }}</h2>
  {% for question in questions %}
    <h3>{{ question.question }}</h3>
  {% endfor %}

  <form action="{{ next_url }}" method="POST">
    {{ form.csrf_token }}
    {{ form.answers(name='answer') }}

    {% if prev_url %}
      <a href="{{ prev_url }}">Back</a>
    {% endif %}
    {% if next_url %}
      <input type="submit" value="Continue">
   {% else %}
      <a href="#">Finish</a>
    {% endif %}
  </form>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

问题是提交带分页的POST请求。如果当前链接为/survey/1/question?page=2,则表单将提交至/submit/1/question?page=3。为了解决这个问题,我刚刚创建了一个单独的提交路由并在那里处理逻辑。