使用flask_wtf,如下:
python文件:
class SiteForm(FlaskForm): site_name = StringField(u'网站名称', validators=[DataRequired()], render_kw={"class_":"form-control","placeholder":"请输入网站名称"}) class SiteConfigView(BaseView): @expose('/', methods=('GET', 'POST')) def site_info(self): form = SiteForm() if form.validate_on_submit(): flash('设置更新成功!') else: print('invalidate submit') return self.render('admin/site_info.html', form=form)
HMTL模板:
<form action="" method="POST" > <div class="form-group"> <label for="site_name" >{{ form.site_name.label }}</label> <div class="col-md-10"> {{form. site_name }} </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10 submit-row"> <input type="submit" class="btn btn-primary"/> </div> </div> </form>
提交表单打印提示"invalidate submit",也就是form.validate_on_submit()总返回False
from.validate_on_submit() 等价于 request.method==' post ' and from.validate(),理论上验证通过后提交表单后应该是True。
打印form.errors错误提示:
invalidate submit
{'csrf_token': ['The CSRF token is missing.']}
原来是 启用了CSRF token保护验证:CsrfProtect(app)#app项目加载CsrfProtect
所以把{{ form.csrf_token }}加到HMTL模板的form里的就好了:
<form action="" method="POST" > {{ form.csrf_token }} <div class="form-group"> <label for="site_name" >{{ form.site_name.label }}</label> <div class="col-md-10"> {{form. site_name }} </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10 submit-row"> <input type="submit" class="btn btn-primary"/> </div> </div> </form>
留言列表: