Python 表单中的TextField即使在输入日期后也返回空字符串
我使用包含TextField和DateField的表单创建了一个表单。这是我的表格课:Python 表单中的TextField即使在输入日期后也返回空字符串,python,flask,datefield,flask-wtforms,Python,Flask,Datefield,Flask Wtforms,我使用包含TextField和DateField的表单创建了一个表单。这是我的表格课: class SubmitReportForm(Form): projectName=TextField('Name of Project', [Required('Please enter name of the project')]) workDone=TextAreaField('work', [Required('Please state your progress')]) fr
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)
@app.route('/user//submit',methods=['GET','POST'])
@需要登录
def提交(用户名):
form=SubmitReportForm()
if request.method==“GET”:
返回呈现模板(“submit.html”,用户名=用户名,表单=表单)
elif request.method==“POST”:
如果表单已提交():
打印“已提交”
如果form.validate():
打印“已验证”
打印表单错误
if form.validate_on_submit():
项目=form.projectName.data
fromDate=form.fromDate.data
toDate=form.toDate.data
进度=form.workDone.data
报告=写入文件(当前用户名、项目、fromDate、toDate、进度)
收件人=['blah@blah.com']
主题=“月度报告人:”+当前用户用户名
msg=消息(主题,发件人=(当前用户名,'blah@blah.com“),收件人=收件人)
msg.body=“请通过“+current_user.userName”查找所附报告
使用app.open_资源(report.name)作为fp:
msg.attach(report.name,“text/plain”,fp.read())
邮件发送(msg)
返回呈现模板('successSubmit.html')
其他:
闪存(u'请填写所有字段','错误')
返回呈现模板(“submit.html”,用户名=用户名,表单=表单)
现在,当我单击submit按钮时,form.validate\u on\u submit()总是返回false。
经过一些调试后,我发现表单已提交但未验证,因为form.fromDate.data始终返回一个None-type对象,即使在表单中输入了日期
我的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 %}
{%extends'base.html%}
{%block content%}
{%with messages=get_flashed_messages()%}
{%if消息%}
{消息%中的消息为%s}
{{message}}
{%endfor%}
{%endif%}
{%endwith%}
{{form.hidden_tag()}}
项目名称:{{form.projectName}
开始日期:{form.fromDate}
结束日期:{form.toDate}
完成进度:{form.workDone(style=“宽度:699px;高度:297px;”)}
{%endblock%}
即使我用TextField代替DateFields,我也会得到一个空字符串。所以请告诉我哪里出了问题??Thanx。您的模板中是否有
{{form.csrf\u token}
(您可以将其放入表单中)。试一下,也许可以工作。。。如果你已经做了,那么。。。我刚刚遇到一个问题,它是由CSRF引起的,所以我添加了这个变量,它就工作了。以下代码应该很有用:
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(在“模板”文件夹中):
{{form.foo_date.label}:{{form.foo_date}}{{form.foo_date.description}
{如果提交日期为%}
您成功提交了以下日期:{{submitted_date}
{%endif%}
{%if form.errors%}
错误
{{form.errors}
{%endif%}
小心,当请求方法是POST时,您没有正确初始化form类(请参见我的代码)。fromDate=form.fromDate.data
可能需要括号:fromDate=form.fromDate.data()
现在的编码方式,您只需引用函数,它返回的值不是toDate=form.toDate.data
和progress=form.workDone.data
似乎遇到了相同的问题。没有,只有fromDate和toDate不返回任何值,progress=form.workDone.data返回正确的数据,因此这不是由于括号造成的。我似乎无法重现您的问题。你的意见是什么?使用表单日期YYYY-MM-DD
,对我来说表单验证没有任何问题。{{form.hidden_tag()}
负责CSRF令牌()。
<!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>