在使用Field的时候,经常需要传递一些参数进去,以下将对一些常用的参数进行解释:
# forms.py
from flask_wtf.file import FileField,FileAllowed,FileRequired
class UploadForm(FlaskForm):
avatar = FileField(u'头像:',validators=[FileRequired(),FileAllowed([])])
# app.py
@app.route('/profile/',methods=('POST','GET'))
def profile():
form = ProfileForm()
if form.validate_on_submit():
filename = secure_filename(form.avatar.data.filename)
form.avatar.data.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
return u'上传成功'
return render_template('profile.html',form=form)
# form.py
class RegistrationForm(FlaskForm):
gender = wtforms.RadioField(u'性别:',validators=[DataRequired()])
模板文件代码如下:
<tr>
<td>
{{ form.gender.label }}
</td>
<td>
{% for gender in form.gender %}
{{ gender.label }}
{{ gender }}
{% endfor %}
</td>
</tr>
app.py文件的代码如下,给gender添加了choices:
@app.route('/register/',methods=['POST','GET'])
def register():
form = RegistrationForm()
form.gender.choices = [('1',u'男'),('2',u'女')]
if form.validate_on_submit():
return u'success'
return render_template('register.html',form=form)
# forms.py
class ProfileForm(FlaskForm):
language = wtforms.SelectField('Programming Language',choices=[('cpp','C++'),('py','python'),('text','Plain Text')],validators=[DataRequired()])
再来看app.py文件:
@app.route('/profile/',methods=('POST','GET'))
def profile():
form = ProfileForm()
if form.validate_on_submit():
print form.language.data
return u'上传成功'
return render_template('profile.html',form=form)
return render_template('profile.html',form=form)
模板文件为:
<form action="/profile/" method="POST">
{{ form.csrf_token }}
{{ form.language.label }}
{{ form.language() }}
<input type="submit">
</form>
数据发送过来,经过表单验证,因此需要验证器来进行验证,以下对一些常用的内置验证器进行讲解:
使用validate_fieldname(self,field)可以对某个字段进行更加详细的验证,如下:
class ProfileForm(FlaskForm):
name = wtforms.StringField('name',[validators.InputRequired()])
def validate_name(self,field):
if len(field.data) > 5:
raise wtforms.ValidationError(u'超过5个字符')