Flask-WTF Dynamic radiofield is running a new quer

2019-08-08 12:20发布

问题:

I am working on building a multiple choice quiz with Flask-WTF and SQLAlchemy that pulls random quotes and possible answers from a database table. I have been able to do just that. However, when the form is submitted and the chosen answers are saved to a new database table, I am seeing that the actual questions (quotes) and answers have been changed. It looks as if a new query is being run upon form submission. Here is a simple example of what I mean.

Actual Question on the Quiz with Options

Who said..."The sky is blue."

  1. Frank (selected as the answer)
  2. Harry
  3. Anne
  4. Mary

Data Saved to the Database

Question: Who said..."The apple is red."

Chosen Answer: Tom

I'm trying to figure out how to stop the additional query from happening so I can save the data from the questions the user actually sees and answers.

Here is my form:

    class Quiz(FlaskForm):
        q1 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q2 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q3 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q4 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q5 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])

And my view route:

    @app.route('/quiz/', methods=['GET', 'POST'])
    def quiz():
        form = Quiz()
        for field in form:
            if field.type != "RadioField":
                continue
            else:
                pulls = Quotes.query.order_by(func.rand()).limit(1)
                for pull in pulls:
                    answer = pull.speaker
                    option_two = pull.option_two
                    option_three = pull.option_three
                    option_four = pull.option_four
                    question = pull.line_text
                    field.label = pull.line_text
                    field.choices = [("1", answer), ("2", option_two), ("3", option_three), ("4", option_four)]
        if form.validate_on_submit():
            for field in form:
                if field.type == "CSRFTokenField":
                    continue
                else:
                    user_answer = field.data
                    question_id = field.id
                    question_line = field.label
                    correct_answer = answer
                    submission = Responses(question_id, question_line, user_answer, correct_answer)
                    db.session.add(submission)
                    db.session.commit()
            return redirect(url_for('you_passed'))
        return render_template('quiz.html', form=form)

Any help would be appreciated. I'm also open to any suggestions about my current code. I'm new to Python and haven't reached the point of elegance in my coding. Thanks.