📅  最后修改于: 2021-01-02 04:37:12             🧑  作者: Mango
WTF代表WT Forms,旨在为用户提供交互式用户界面。 WTF是烧瓶的内置模块,它提供了在烧瓶Web应用程序中设计表单的另一种方法。
由于以下因素,WTF很有用。
WT Forms是用于提供用户界面的灵活的表单呈现和验证库。
要使用WT表单,我们需要安装flask-wtf库,该库可以使用pip installer安装。
$ pip install flask-wtf
该模块包含一个Form类,该类被视为所有与表单相关的操作的父类。
下面列出了标准表单字段。
SN | Form Field | Description |
---|---|---|
1 | TextField | It is used to represent the text filed HTML form element. |
2 | BooleanField | It is used to represent the checkbox HTML form element. |
3 | DecimalField | It is used to represent the text field to display the numbers with decimals. |
4 | IntegerField | It is used to represent the text field to display the integer values. |
5 | RadioField | It is used to represent the radio button HTML form element. |
6 | SelectField | It is used to represent the select form element. |
7 | TextAreaField | It is used to represent text area form element. |
8 | PasswordField | It is used to take the password as the form input from the user. |
9 | SubmitField | It provides represents the html form element. |
考虑以下示例。
在此示例中,我们将使用flask WTF模块创建一个表单。首先,我们将创建一个名为forms.py的表单类,并将这些表单元素导入模块formexample.py中。
表格
from flask_wtf import Form
from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField
from wtforms import validators, ValidationError
class ContactForm(Form):
name = TextField("Candidate Name ",[validators.Required("Please enter your name.")])
Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')])
Address = TextAreaField("Address")
email = TextField("Email",[validators.Required("Please enter your email address."),
validators.Email("Please enter your email address.")])
Age = IntegerField("Age")
language = SelectField('Programming Languages', choices = [('java', 'Java'),('py', 'Python')])
submit = SubmitField("Submit")
formexample.py
from flask import Flask, render_template, request, flash
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'development key'
@app.route('/contact', methods = ['GET', 'POST'])
def contact():
form = ContactForm()
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form = form)
@app.route('/success',methods = ['GET','POST'])
def success():
return render_template("success.html")
if __name__ == '__main__':
app.run(debug = True)
contact.html
Registration Form
{% for message in form.name.errors %}
{{ message }}
{% endfor %}
{% for message in form.email.errors %}
{{ message }}
{% endfor %}
Success.html
Form posted successfully
输出: