3.3 Web Forms:
Web Forms are the basic functionality of Web applications.
It is the part of the HTML page that is responsible for data collection. The form has three parts: a form label, a form field, and a form button. Forms allow users to enter data, take care of HTML page data collection, and submit data entered by the user to the server through a form.
In flask, in order to work with Web forms, we generally use the FLASK-WTF extension, which encapsulates wtforms, and it has the capability to validate form data.
Wtforms Supported HTML standard fields
Field Object |
Description |
Stringfield |
Text field |
Textareafield |
Multi-line Text field |
Passwordfield |
Password text field |
HiddenField |
Hide text fields |
Datefield |
Text field with a value of datetime.date format |
Datetimefield |
Text field with a value of datetime.datetime format |
Integerfield |
Text field with a value of integer |
Decimalfield |
A text field with a value of decimal. Decimal |
Floatfield |
Text field, value is floating point |
Booleanfield |
check box with a value of true and False |
Radiofield |
A group of radio boxes |
Selectfield |
drop-down list |
Selectmultiplefield |
Drop-down list, multiple values can be selected |
Filefield |
Text Upload field |
Submitfield |
Form Submit button |
FormField |
Embed a form as a field into another form |
FieldList |
A set of fields of the specified type |
Wtforms Common validation functions
validation Functions |
Description |
DataRequired |
Make sure there is data in the field |
Equalto |
Compares the values of two fields and is commonly used to compare two password entries |
Length |
Verify the string length of the input |
Numberrange |
Verify that the value entered is within the range of numbers |
Url |
Verify URL |
AnyOf |
Verify that the input values are in the optional list |
Noneof |
Verify that the input value is not in the optional list |
Use FLASK-WTF to configure the parameter Secret_key.
Csrf_enabled is for CSRF (cross-site request forgery) protection. Secret_key is used to generate an encryption token that, when CSRF is activated, generates an encryption token based on the key set.
Write the form form directly in the HTML page:
#template file<form method='Post'> <input type="text"Name="username"Placeholder='Username'> <input type="Password"Name="Password"Placeholder='Password'> <input type="Submit"></form>
To get the form data in the View function:
fromFlaskImportFlask,render_template,request@app.route ('/login', methods=['GET','POST'])deflogin ():ifRequest.method = ='POST': Username= request.form['username'] Password= request.form['Password'] PrintUsername,passwordreturnRender_template ('login.html', Method=request.method)
Implement the form using FLASK-WTF. Configuration parameters:
app.config['secret_key'silents is gold'
Template page:
<form method="post"> # settings 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 in get_flashed_messages ()% } {{x}} {% endfor%</form>
View functions:
#Coding=utf-8 fromFlaskImportflask,render_template, Redirect,url_for,session,request,flash#importing form classes for WTF extensions fromFlask_wtfImportFlaskform#import fields required for custom forms fromWtformsImportSubmitfield,stringfield,passwordfield#Import the form validator provided by the WTF extension fromWtforms.validatorsImportDatarequired,equaltoapp= Flask (__name__) app.config['Secret_key']='1'#custom Form class, Text field, password field, submit buttonclassLogin (Form): US= Stringfield (label=u'User:', validators=[DataRequired ()]) PS= Passwordfield (label=u'Password', validators=[datarequired (), Equalto ('PS2','Err')]) PS2= Passwordfield (label=u'Confirm Password', validators=[DataRequired ()]) Submit= Submitfield (U'Submit') @app. Route ('/login')deflogin ():returnRender_template ('login.html')#define root route view functions, Generate form objects, get form data, perform form data validation@app. Route ('/', methods=['GET','POST'])defindex (): Form=Login ()ifform.validate_on_submit (): Name=Form.us.data pswd=Form.ps.data pswd2=Form.ps2.dataPrintNAME,PSWD,PSWD2returnRedirect (Url_for ('Login')) Else: ifrequest.method=='POST': Flash (U'information is wrong, please re-enter! ') PrintForm.validate_on_submit ()returnRender_template ('index.html', form=form)if __name__=='__main__': App.run (Debug=true)
Flask Template Web Form