我使用包含TextField和DateField的烧瓶wtforms创建了一个表单。这是我的表单类:
class SubmitReportForm(Form):
projectName=TextField('Name of Project', [Required('Please enter name of the project')])
workDone=TextAreaField('work', [Required('Please state your progress')])
fromDate=DateField('fromDate', [Required('Please mention a start date')])
toDate=DateField('toDate', [Required('Please mention an end date')])
submit=SubmitField('Submit')
我处理此表单的视图函数是:
@app.route('/user/<userName>/submit', methods=['GET', 'POST'])
@login_required
def submit(userName):
form=SubmitReportForm()
if request.method=='GET' :
return render_template("submit.html", userName=userName, form=form)
elif request.method =='POST' :
if form.is_submitted():
print 'submitted'
if form.validate():
print 'validated'
print form.errors
if form.validate_on_submit():
project=form.projectName.data
fromDate=form.fromDate.data
toDate=form.toDate.data
progress=form.workDone.data
report=writeToFile(current_user.userName, project, fromDate, toDate, progress)
recipient=['blah@blah.com']
subject="Monthly report by : " + current_user.userName
msg = Message(subject, sender =(current_user.userName, 'blah@blah.com'), recipients = recipient)
msg.body= "Please find the attached report by "+ current_user.userName
with app.open_resource(report.name) as fp:
msg.attach(report.name, "text/plain", fp.read())
mail.send(msg)
return render_template('successSubmit.html')
else:
flash(u'Please fill all the fields', 'error')
return render_template("submit.html", userName=userName, form=form)
现在,当我单击提交按钮时,form.validate_on_submit() 总是返回 false。经过一些调试,我发现表单已提交但未验证,因为即使在表单中输入日期后,form.fromDate.data 也始终返回 None 类型对象。
我的 HTML 文件:
{% extends 'base.html' %}
{% block content %}
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<p><span style="color: red;">{{ message }}</span></p>
{% endfor %}
{% endif %}
{% endwith %}
<form action ='{{url_for('submit', userName=userName)}}' method='POST'>
{{form.hidden_tag()}}
<p>
Project Name: {{form.projectName}}
</p>
<br>
<p>
<label>Start Date : </label> {{form.fromDate}}
</p>
<br>
<p>
<label>End Date : </label> {{form.toDate}}
</p>
<br>
<p>
Progress Done: {{form.workDone(style="width: 699px; height: 297px;")}}
</p>
<br>
<p>
<input type='submit' value='Send Report'>
</p>
<br>
</form>
{% endblock %}
即使我使用文本字段代替日期字段,我也会得到一个空字符串。所以请告诉我我哪里出错了??提前感谢。
以下代码应该很有用:
from flask import Flask, render_template, request
from wtforms import Form
from wtforms.fields import DateField
from wtforms.validators import Required
app = Flask(__name__)
app.config['DEBUG'] = True
class TestForm(Form):
foo_date = DateField('Foo Date',
[Required('Foo Date is required')],
format='%Y-%m-%d',
description='Date format: YYYY-MM-DD')
@app.route("/", methods=['GET', 'POST'])
def index():
submitted_date = None
if request.method == 'POST':
form = TestForm(request.form) # PAY ATTENTION HERE
if form.validate():
submitted_date = form.foo_date.data
else:
form = TestForm()
return render_template('tpl.html', form=form, submitted_date=submitted_date)
if __name__ == "__main__":
app.run()
模板 tpl.html(在"模板"文件夹中):
<!DOCTYPE html>
<html>
<body>
<form method='POST' action=''>
<p>{{ form.foo_date.label }}: {{ form.foo_date }} {{ form.foo_date.description }}</p>
<input type='submit' value='Send foo date'>
</form>
{% if submitted_date %}
<p style="color: green">You submitted successfully the following date: {{ submitted_date }}</p>
{% endif %}
{% if form.errors %}
<h2>Errors</h2>
<p style="color: red">{{ form.errors }}</p>
{% endif %}
</body>
</html>
请注意,当请求方法是 POST 时,您没有正确初始化表单类(请参阅我的代码)。
您的模板中是否有{{ form.csrf_token }}
(您可以将其放在form
中)。试一试,也许可以工作...如果你已经完成了,那么...我刚刚遇到了一个问题,它是由 CSRF 引起的,所以我添加了这个变量并且它起作用了。