📜  在 Flask 中使用 WTForms 创建联系我们

📅  最后修改于: 2022-05-13 01:55:01.861000             🧑  作者: Mango

在 Flask 中使用 WTForms 创建联系我们

WTForms是一个旨在使表单处理更易于管理的库。它非常容易地处理浏览器提交的数据。在本文中,我们将讨论如何使用 WTForms 创建联系我们表单。

WT-FORM的优点:

  1. 我们不必担心验证器。
  2. 避免跨站请求伪造 (CSRF)。
  3. WTForms 作为类出现,所以所有的好处都来自对象形式。
  4. 无需使用 HTML 手动创建任何

安装

使用终端安装 Flask-WTF。

pip install Flask-WTF

分步实施

第 1 步:在 main.py 中创建一个类,其中包含您想要的表单中的所有元素。

Python3
from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
import email_validator
  
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(label='Email', validators=[
      DataRequired(), Email(granular_message=True)])
       message= StringField(label='Message')
    submit = SubmitField(label="Log In")


Python3
@app.route("/", methods=["GET", "POST"])
def home():
    cform = contactForm()
    return render_template("contact.html", form=cform)


HTML

  

    
        Contact
    
    
        
            

Contact Us

            
                {{ form.csrf_token }}                                    

                    {{ form.name.label }}                      
                    {{ form.name }}                 

                                         

                    {{ form.email.label }}                      
                    {{ form.email(size=30) }}                 

                                         

                    {{ form.message.label }}                      
                    {{ form.message }}                 

                   {{ form.submit }}             
        
    


Python3
@app.route("/", methods=["GET", "POST"])
def home():
    cform = contactForm()
    if cform.validate_on_submit():
        print(f"Name:{cform.name.data}, 
              E-mail:{cform.email.data}, 
              message:{cform.message.data}")
    else:
        print("Invalid Credentials")
                
    return render_template("contact.html", form=cform)


Python3
from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
import email_validator
  
app = Flask(__name__)
app.secret_key = "any-string-you-want-just-keep-it-secret"
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(
      label='Email', validators=[DataRequired(), Email(granular_message=True)])
    message = StringField(label='Message')
    submit = SubmitField(label="Log In")
  
  
@app.route("/", methods=["GET", "POST"])
def home():
    cform=contactForm()
    if cform.validate_on_submit():
            print(f"Name:{cform.name.data}, E-mail:{cform.email.data},
                  message:{cform.message.data}")
    return render_template("contact.html",form=cform)
  
  
if __name__ == '__main__':
    app.run(debug=True)


HTML



    
    {% block title %}{% endblock %}


    {% block content %}{% endblock %}



HTML
{% extends 'bootstrap/base.html' %}
{% import "bootstrap/wtf.html" as wtf %}
  
{% block title %}
Contact Us
{% endblock %}
  
{% block content %}
        
            

Contact Us

            {{ wtf.quick_form(form) }}         
{% endblock %}l>


Python3
from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
from flask_bootstrap import Bootstrap
import email_validator
app = Flask(__name__)
Bootstrap(app)
app.secret_key = "any-string-you-want-just-keep-it-secret"
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(label='Email', validators=[DataRequired(), Email(granular_message=True)])
    message = StringField(label='Message')
    submit = SubmitField(label="Log In")
  
  
@app.route("/", methods=["GET", "POST"])
def home():
    cform=contactForm()
    if cform.validate_on_submit():
            print(f"Name:{cform.name.data}, E-mail:{cform.email.data}, message:{cform.message.data}")
    return render_template("contact.html",form=cform)
  
  
if __name__ == '__main__':
    app.run(debug=True)


第二步:创建表单的对象,并将对象作为参数传入render_template



蟒蛇3

@app.route("/", methods=["GET", "POST"])
def home():
    cform = contactForm()
    return render_template("contact.html", form=cform)

第 3 步:添加 CSRF 保护。添加密钥。

app.secret_key = "any-string-you-want-just-keep-it-secret"

第 4 步:在 contact.html HTML 文件中添加字段。

{{ form.csrf_token }} is used to provide csrf protection.

HTML


  

    
        Contact
    
    
        
            

Contact Us

            
                {{ form.csrf_token }}                                    

                    {{ form.name.label }}                      
                    {{ form.name }}                 

                                         

                    {{ form.email.label }}                      
                    {{ form.email(size=30) }}                 

                                         

                    {{ form.message.label }}                      
                    {{ form.message }}                 

                   {{ form.submit }}             
        
    

第 5 步:验证表单并接收数据。

蟒蛇3

@app.route("/", methods=["GET", "POST"])
def home():
    cform = contactForm()
    if cform.validate_on_submit():
        print(f"Name:{cform.name.data}, 
              E-mail:{cform.email.data}, 
              message:{cform.message.data}")
    else:
        print("Invalid Credentials")
                
    return render_template("contact.html", form=cform)

完整代码:

蟒蛇3



from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
import email_validator
  
app = Flask(__name__)
app.secret_key = "any-string-you-want-just-keep-it-secret"
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(
      label='Email', validators=[DataRequired(), Email(granular_message=True)])
    message = StringField(label='Message')
    submit = SubmitField(label="Log In")
  
  
@app.route("/", methods=["GET", "POST"])
def home():
    cform=contactForm()
    if cform.validate_on_submit():
            print(f"Name:{cform.name.data}, E-mail:{cform.email.data},
                  message:{cform.message.data}")
    return render_template("contact.html",form=cform)
  
  
if __name__ == '__main__':
    app.run(debug=True)

输出:

Name:Rahul Singh, E-mail:rahuls@gmail.com, message:This is Sample gfg Output!!!

添加引导程序

我们还可以将引导程序添加到上述表单中,使其看起来具有交互性。为此,我们将使用 Flask-Bootstrap 库。要安装此模块,请在终端中键入以下命令。

pip install Flask-Bootstrap

第 1 步:创建 base.html

HTML




    
    {% block title %}{% endblock %}


    {% block content %}{% endblock %}


Steo 2:修改contact.html为

with single line {{ wtf.quick_form(form) }}

HTML

{% extends 'bootstrap/base.html' %}
{% import "bootstrap/wtf.html" as wtf %}
  
{% block title %}
Contact Us
{% endblock %}
  
{% block content %}
        
            

Contact Us

            {{ wtf.quick_form(form) }}         
{% endblock %}l>

第三步:修改main.py

修改.py文件非常简单。我们只需要导入模块并将以下行添加到代码中

Bootstrap(app)

蟒蛇3

from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, validators, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email
from flask_bootstrap import Bootstrap
import email_validator
app = Flask(__name__)
Bootstrap(app)
app.secret_key = "any-string-you-want-just-keep-it-secret"
  
class contactForm(FlaskForm):
    name = StringField(label='Name', validators=[DataRequired()])
    email = StringField(label='Email', validators=[DataRequired(), Email(granular_message=True)])
    message = StringField(label='Message')
    submit = SubmitField(label="Log In")
  
  
@app.route("/", methods=["GET", "POST"])
def home():
    cform=contactForm()
    if cform.validate_on_submit():
            print(f"Name:{cform.name.data}, E-mail:{cform.email.data}, message:{cform.message.data}")
    return render_template("contact.html",form=cform)
  
  
if __name__ == '__main__':
    app.run(debug=True)

输出: