Skip to content Skip to sidebar Skip to footer

Python/flask-wtf - How Can I Randomize The Choices From Dynamic Radiofield?

I am looking to build a multiple choice quiz using python/flask/flask-wtf. I am successfully able to pull random questions from a database as well as pull random choices as the pos

Solution 1:

You could try dynamically extending your FlaskForm:

defQuiz(number_of_questions):
    class_Quiz(FlaskForm):
        passfor n inrange(number_of_questions):
        setattr(_Quiz, RadioField('Label', choices=[]), 'question_' + str(n))
    return _Quiz()

Now your form has a question_[n] attribute for each question so you can iterate it in jijna2:

<div class="quote-block">
<formmethod="POST">
{{ form.hidden_tag() }}
{% for q_num in range(n) %}
    {{ quotes[q_num].line_text }}
    {{ form['question_' + q_num|string }}
{% endfor %}
<inputtype="submit"></form></div>

Solution 2:

After a lot of reading and research, I realized I was trying to do too much too soon. So I took a step back and built the blocks of what I was trying to do and then it finally came together. Of course, I am having new issues with the form validation portion, but I'll include that in a new question.

My biggest roadblock was that I was trying to pull random choice options for the RadioField. Instead, I added three columns to the database table and supplied the options in the table. That made it easier to pull the options and the question with one query.

Basically, I am running a for loop over the fields in the form. If the field is a RadioField, it runs a query against the database and pulls a random row. I then use another for loop over the pulled row and assign different elements to the pieces of the RadioField (label, choices).

If you know of a more elegant way to do this, I'd love to hear it. But for now it works.

My form and template stayed the same. But here is my new route view.

@app.route('/quiz/', methods=['GET', 'POST'])
    def quiz():
        form = Quiz()
        for field in form:
            if field.type != "RadioField":
                continueelse:
                pulls = Quotes.query.order_by(func.rand()).limit(1)
                for pull in pulls:
                    answer = pull.speakeroption_two= pull.option_twooption_three= pull.option_threeoption_four= pull.option_fourquestion= pull.line_text
                    field.label = pull.line_text
                    field.choices = [(answer, answer), (option_two, option_two), (option_three, option_three), (option_four, option_four)]
            return redirect(url_for('you_passed'))
        return render_template('television/quiz.html', form=form)

Post a Comment for "Python/flask-wtf - How Can I Randomize The Choices From Dynamic Radiofield?"