0.前言
最近在完善自己的blog中的post功能,其中碰到一个小问题--post创建的提交时,
form.validate()
的结果always false.
后来查阅资料(flask-wtforms-validation-always-false 和官方资料),发现是html模版中有几个字段没有加入渲染,导致渲染时传入值为空。
于是想回过头了加深一下有关表单基础知识。
1.表单基本了解
在flask框架中,Flask-WTF是一个集成了WTForms的Flask扩展,我们可以使用它进行创建表单类,然后在HTML使用它提供的函数渲染表单。
表单创建:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, Length, Email
class PostForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
category = StringField('Category')
content = TextAreaField('Content')
post_id = HiddenField('post_id')
submit = SubmitField('submit')
接下来,在视图函数中,引入表单实例并返回相应的模版
class Post(MethodView):
decorators = [login_required, writer_Permission.require(401)]
template_name = "blog_admin/post.html"
...
def post(self, args):
form = forms.PostForm(request.form)
if not form.validate():
...
return render_template(self.template_name, form=form)
表单渲染:
两种方式:
-
flask-bootstrap渲染(《Flask Web开发:基于Python的Web应用开发实战》经常用到)
-
一般渲染(常用)
flask-boostrap是bootstrap的flask扩张,它可以提供wtf.html文件中的form_field函数来进行渲染:
{% import "bootstrap/wtf.html" as wtf %}
<form class="form" method="POST">
{{ form.hidden_tag() }}
{{ wtf.form_field(form.title) }}
{{ wtf.form_field(form.content) }}
...
{{ wtf.form_field(form.submit) }}
</form>
注意,如果有多个隐藏字段,可以使用form.hidden_tag()渲染所以隐藏字段。
另外Flask-WTF支持跨站请求伪造保护,表单类创建时会自动创建一个CSRF字段,你需要在表单里渲染这个字段:{{ form.csrf_token }}。
还有一种快速渲染方式:
{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}
一般渲染:
直接在对应的html模版中引入字段:
<form class="form" method="POST">
{{ form.hidden_tag() }}
{{ form.title.label }}{{ form.title() }}
{{ form.content.label }}{{ form.content() }}
{{ form.submit() }}
</form>
另外还可以在字段中加入有些属性,比如要加入class:
form.title(class_="form-control")
转化为html的效果:
<input type="text" name="title" value="title" class="form-control" id="title" />
上面的渲染如果有很多字段的话,一个个写出来会觉得很繁琐,在实际开发中,可以创建一个_form.html文件来处理。
_form.html
:
{% macro render(form) -%}
{% for field in form %}
{% if field.type in ['CSRFTokenField', 'HiddenField'] %}<!--CSR和隐藏字段-->
{{ field() }}
{% elif field.type == "BooleanField" %}<!--Boolean类型字段-->
<div class="checkbox">
<label>
{{ field() }} {{ field.label }}
</label>
</div>
{% elif field.type == "RadioField" %}<!--Radio类型字段-->
{{ field.label }}
{% for subfield in field %}
<div class="radio">
<label>{{ subfield }} {{ subfield.label }}</label>
</div>
{% endfor %}
{% else %}
<div class="clearfix {% if field.errors %}has-error{% endif %} form-group"><!--剩下的一般类型字段-->
{{ field.label }}
{% if field.type == "TextAreaField" %}
{{ field(class_="form-control", rows=10) }}
{% else %}
{{ field(class_="form-control") }}
{% endif %}
{% if field.errors or field.help_text %}
<span class="help-block">
{% if field.errors %}
{{ field.errors|join(' ') }}
{% else %}
{{ field.help_text }}
{% endif %}
</span>
{% endif %}
</div>
{% endif %}
{% endfor %}
{% endmacro %}
接着在对应的html模版中进行引用 :
{% import "_form.html" as forms %}<!--引入_form-->
<form method="POST" action="">
{{ forms.render(form) }}<!--使用_form对form来进行渲染-->
总结:
flask表单实现其实不难,只要多实践,多花时间研究源码,并且多思考,很快就可以掌握的。
参考链接:
1.https://greyli.com/flask-form-create-and-render/
2.WTForms官方文档
3.http://flask.pocoo.org/docs/1.0/patterns/wtforms/
4.https://stackoverflow.com/questions/20905188/flask-wtforms-validation-always-false