flask表单

一、原生表单

模板页面

<form action="{{ url_for('check') }}" method="post">
    <p>用户名: <input type="text" name="username"></p>
    <p>密码: <input type="password" name="userpass"></p>
    <p><input type="submit" value="submit"></p>
</form>

  

在manage.py中

#原生表单
@app.route('/form1')
def form1():
    return render_template('form1.html')
​
#获取原生表单提交的数据
@app.route('/check',methods=['POST'])
def check():
    print(request.form.get('userpass'))
    print(request.form.get('username'))
    return '提交过来了'

  

将manage.py中的俩个路由合并为同一个

 
@app.route('/form1',methods=['GET','POST'])
def form1():
    if request.method == 'POST':
        print(request.form.get('userpass'))
        print(request.form.get('username'))
    return render_template('form1.html')

  

二、FLASK-WTF

说明: 是一个用于表单处理,校验 ,提供了csrf等功能

安装: sudo pip3 install flask-wtf

(1) 字段类型

字段类型 字段说明
StringField 普通文本字段
SubmitField 提交
PasswordField 密码字段
TextAreaField 多行文本域字段
DateField 日期字段 datetime.date
DateTimeFiled 时间时期 datetime.datetime
HiddenField 隐藏域字段
IntegerField 数值字段
FloatField 小数字段
BooleanField bool字段 True和False
RadioFIeld 单选字段
SelectField 下拉字段
FileField 文件上传字段

(2) 验证器

验证器名称 说明
DataRequired 必填
Email 验证邮箱
IPAddress 验证ip地址 默认ipv4
Length 验证当前值的长度 min 和max
NumberRange 数值的范围 提供了 min 和max
EqualTo 验证俩个输入框的值是否相同
URL 验证是否为有效的url地址
Regexp 正则匹配

(3) 实例 wtf_表单

模板文件 form.html

<form action="{{ url_for('wtf_form') }}" method="post">
        {{ form.csrf_token }}
        <p>{{ form.username.label() }}{{ form.username(style='color:red;',placeholder='请输入用户名...') }}</p>
        <p>{{ form.userpass.label() }}{{ form.userpass() }}</p>
        <p>{{ form.submit() }}</p>
</form>

  

manage.py

 
class Login(FlaskForm):
    username = StringField('用户名',validators=[Length(min=6,max=12,message='用户名长度为6~12位'),DataRequired(message='用户名不能为空')])
    userpass = PasswordField('密码',validators=[Length(min=6,max=12,message='密码长度为6~12位'),DataRequired(message='密码不能为空')])
    submit = SubmitField('登录')
    
​
@app.route('/wtf_form',methods=['GET','POST'])
def wtf_form():
    form = Login()
    if request.method == 'POST':
        if form.validate_on_submit():
            print(request.form.get('userpass'))
            print(request.form.get('username'))
            return '数据提交成功'
    return render_template('wtf_form.html',form=form)

  

注意:

form.validate_on_submit() 只有在数据正确 并且验证csrf通过 才为真

(4) 使用bootstrap快速渲染

导入

 
{% import 'bootstrap/wtf.html' as wtf %}

  

模板文件

{{ wtf.quick_form(form,url_for('form1')) }}
{{ wtf.quick_form(form) }}

  

manage.py路由 不变

猜你喜欢

转载自www.cnblogs.com/jixiaoleng4/p/9113015.html
今日推荐