Web form is the basic component of a web application. It is a part of an HTML web page that is responsible for data collection. A web form consists of three parts: a form label, a form field, and a form button. Forms allow users to enter data and submit the user-entered data to web server.
1. How To Process Web Form In Flask.
In Flask, in order to process web forms, we usually use the Flask-WTF extension, which encapsulates WTForms and has the function of verifying form data.
1.1 Verification Functions Commonly Used In WTForms.
- AnyOf: Verify that the input value is in the optional list.
- DateRequired: Make sure there is data in the field.
- EqualTo: Compare the values of two fields. It is often used to compare the input of two passwords.
- Length: Verify the length of the input string.
- NoneOf: Verify that the input value is not in the optional list.
- NumberRange: Verify that the value entered is in the numeric range.
- URL: Verify URL.
1.2 HTML Standard Fields Supported By WTForms.
- BooleanField: Checkbox, value is true or false.
- DateField: Text field, value is
datetime.date
text format. - DateTimeField: Text field, value is
datetime.datetime
text format. - DecimalField: Text field with a
decimal.Decimal
value. - FieldList: A set of fields of a specified type.
- FileField: File upload field.
- FloatField: Text field with floating point value.
- FormField: Embed a form as a field into another form.
- HiddenField: Hide file field.
- IntegerField: Text field with an integer value.
- PasswordField: Password text field.
- RadioField: A set of radio buttons.
- SelectField: Dropdown list.
- SelectMutipleField: A drop-down list that can select multiple values.
- StringField: Text field.
- SubmitField: Form submit button.
- TextAreaField: Multiline text field.
2. Use Flask-WTF To Implement Web Form.
2.1 Configure SECRET_KEY.
CSRF_ENABLED is used for CSRF (Cross-Site Request Forgery) protection. SECRET_KEY is used to generate encryption tokens. When CSRF is activated, this setting will generate an encryption token based on the secret key.
app.config['SECRET_KEY'] = 'SECRET_KEY'
2.2 Web Page Template.
<form method="post"> # set csrf_token {{ form.csrf_token() }} {{ form.us.label }} <p>{{ form.us }}</p> {{ form.ps.label }} <p>{{ form.ps }}</p> {{ form.ps2.label }} <p>{{ form.ps2 }}</p> <p>{{ form.submit() }}</p> {% for x in get_flashed_messages() %} {{ x }} {% endfor %} </form>
2.3 Flask View Function.
#coding=utf-8 # Import required Flask library and module. from flask import Flask,render_template,redirect,url_for,session,request,flash # Import form class of WTF extension from flask_wtf import FlaskForm # Import form fields class required by custom form. from wtforms import SubmitField,StringField,PasswordField # Import form field validator provided by WTF extension. from wtforms.validators import DataRequired,EqualTo app = Flask(__name__) app.config['SECRET_KEY']='1' # Create a custom web form login class, it conatins user name text field, password field, submit button. class Login(FlaskForm): username = StringField(label=u'User Name',validators=[DataRequired()]) passwd = PasswordField(label=u'Password',validators=[DataRequired(),EqualTo('passwd2','err')]) passwd2 = PasswordField(label=u'Confirm Password',validators=[DataRequired()]) submit = SubmitField(u'Submit') @app.route('/login',methods=['GET','POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] print('username = ' + username) print('password = ' + password) return render_template('login.html',method=request.method) # Define the root route view function, generate the form object, obtain and verify the form data. @app.route('/',methods=['GET','POST']) def index(): # Create the form object. form = Login() # Verify the form field data. if form.validate_on_submit(): # Get form field data. username = form.username.data passwd = form.passwd.data passwd2 = form.passwd2.data print('username = ' + username) print('passwd = ' + passwd) print('passwd2 = ' + passwd2) return redirect(url_for('login')) else: if request.method=='POST': flash(u'Form field value error, please input again.') # Print form field error message. print(form.validate_on_submit()) return render_template('index.html',form=form) if __name__ == '__main__': app.run(debug=True)