kratos2333
2/20/2019 - 8:40 PM

Flask WTF Form with more type of fields

from flask import Flask, render_template, session, redirect, url_for, session
from flask_wtf import FlaskForm
from wtforms import (StringField, BooleanField, DateTimeField,
                     RadioField,SelectField,TextField,
                     TextAreaField,SubmitField)
from wtforms.validators import DataRequired


app = Flask(__name__)
# Configure a secret SECRET_KEY
# We will later learn much better ways to do this!!
app.config['SECRET_KEY'] = 'mysecretkey'

# Now create a WTForm Class
# Lots of fields available:
# http://wtforms.readthedocs.io/en/stable/fields.html
class InfoForm(FlaskForm):
    '''
    This general class gets a lot of form about puppies.
    Mainly a way to go through many of the WTForms Fields.
    '''
    breed = StringField('What breed are you?',validators=[DataRequired()])
    neutered  = BooleanField("Have you been neutered?")
    mood = RadioField('Please choose your mood:', choices=[('mood_one','Happy'),('mood_two','Excited')])
    food_choice = SelectField(u'Pick Your Favorite Food:',
                          choices=[('chi', 'Chicken'), ('bf', 'Beef'),
                                   ('fish', 'Fish')])
    feedback = TextAreaField()
    submit = SubmitField('Submit')



@app.route('/', methods=['GET', 'POST'])
def index():

    # Create instance of the form.
    form = InfoForm()
    # If the form is valid on submission (we'll talk about validation next)
    if form.validate_on_submit():
        # Grab the data from the breed on the form.

        session['breed'] = form.breed.data
        session['neutered'] = form.neutered.data
        session['mood'] = form.mood.data
        session['food'] = form.food_choice.data
        session['feedback'] = form.feedback.data

        return redirect(url_for("thankyou"))  # note that redirect(url_for...) is used for going to another flask routing method !


    return render_template('01-home.html', form=form)


@app.route('/thankyou')
def thankyou():

    return render_template('01-thankyou.html')


if __name__ == '__main__':
    app.run(debug=True)

<h1>Welcome to Puppy Surveys</h1>
<form  method="POST">
    {# This hidden_tag is a CSRF security feature. #}
    {{ form.hidden_tag() }}
    {{ form.breed.label }} {{form.breed}}
    <br>
    {{ form.neutered.label}} {{form.neutered}}
    <br>
    {{form.food_choice.label}}{{form.food_choice}}
    <br>
    {{form.mood.label}}{{form.mood}}
    <br>
    Any other feedback?
    <br>
    {{form.feedback}}
   <br>
    {{ form.submit() }}
</form>

<h1>Thank you. Here is the info you gave:</h1>
<ul>
  <li>Breed: {{session['breed']}}</li>
  <li>Neutered: {{session['neutered']}}</li>
  {# Note, this saves the mood key, not the form value, the saved value is like mooe_one and mood_two!!! #}
  <li>Mood: {{session['mood']}}</li>
  <li>Food: {{session['food']}}</li>
  <li>Feedback: {{session['feedback']}}</li>
</ul>