背景
一个基于FlaskForm的页面,原表格展示如下:
希望在邮箱输入栏中显示一个占位符提示,而非默认输入值。
FlaskForm创建如下:
1 | class AdAdd(FlaskForm): |
页面引用:
1 | <div class="col-md-4 col-md-offset-4"> |
思路
先看一看FlaskForm的field类有哪些属性可以设置:
1 | class wtforms.fields.Field |
参数说明如下:
- label – The label of the field.
- validators – A sequence of validators to call when validate is called.
- filters – A sequence of filters which are run on input data by process.
- description – A description for the field, typically used for help text.
- id – An id to use for the field. A reasonable default is set by the form, and you shouldn’t need to set this manually.
- default – The default value to assign to the field, if no form or object input is provided. May be a callable.
- widget – If provided, overrides the widget used to render the field.
- render_kw (dict) – If provided, a dictionary which provides default keywords that will be given to the widget at render time.
- _form – The form holding this field. It is passed by the form itself during construction. You should never pass this value yourself.
- _name – The name of this field, passed by the enclosing form during its construction. You should never pass this value yourself.
- _prefix – The prefix to prepend to the form name of this field, passed by the enclosing form during construction.
- _translations – A translations object providing message translations. Usually passed by the enclosing form during construction. See I18n docs for information on message translations.
- _meta – If provided, this is the ‘meta’ instance from the form. You usually don’t pass this yourself.
可以发现有一个description参数,那么尝试配置description参数:
1 | class AdAdd(FlaskForm): |
结果展示如下:
可见是在表格的下放出现一个提醒文本框,虽然起到一定的作用,但是并非我们想要的效果。
再看render_kw这个参数,它可以在渲染展示的时候传递字典参数进行渲染你,而placeholder是html的一个参数,那么尝试通过render_kw的方式,看看是否可以渲染出来。
代码修改为:
1 | class AdAdd(FlaskForm): |
结果展示如下:
效果实现成功。
扩展
根据上述实现过程,我们可以发现,通过render_kw
基本上我们可以把html中可以个性化的一些参数以dict的形式传递,从而显示更多我们想要的效果。
FlaskForm是基于WTForms,其他更多信息可参考:https://wtforms.readthedocs.io/en/stable/fields.html#the-field-base-class