How To Process Web Form In Flask

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.

  1. AnyOf: Verify that the input value is in the optional list.
  2. DateRequired: Make sure there is data in the field.
  3. EqualTo: Compare the values of two fields. It is often used to compare the input of two passwords.
  4. Length: Verify the length of the input string.
  5. NoneOf: Verify that the input value is not in the optional list.
  6. NumberRange: Verify that the value entered is in the numeric range.
  7. URL: Verify URL.

1.2 HTML Standard Fields Supported By WTForms.

  1. BooleanField: Checkbox, value is true or false.
  2. DateField: Text field, value is datetime.date text format.
  3. DateTimeField: Text field, value is datetime.datetime text format.
  4. DecimalField: Text field with a decimal.Decimal value.
  5. FieldList: A set of fields of a specified type.
  6. FileField: File upload field.
  7. FloatField: Text field with floating point value.
  8. FormField: Embed a form as a field into another form.
  9. HiddenField: Hide file field.
  10. IntegerField: Text field with an integer value.
  11. PasswordField: Password text field.
  12. RadioField: A set of radio buttons.
  13. SelectField: Dropdown list.
  14. SelectMutipleField: A drop-down list that can select multiple values.
  15. StringField: Text field.
  16. SubmitField: Form submit button.
  17. 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)
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x