我尝试使用Flask创建一个基本的会计软件包,我对验证特定表单有点困惑。它适用于同一个应用程序中的另一个表单,但出于某种原因,我无法弄清楚为什么这个表单不能正常工作。表单在Web浏览器中显示为正常,我可以正常输入数据,但是当我提交表单时,它似乎只是重新加载页面。我的数据库没有得到更新,经过一番挖掘,我发现我的if form.validate_on_submit()
没有抓到任何东西。
堆栈跟踪中也没有抛出错误。
我将在下面发布我的文件的相关部分。
我的views.py
:
@app.route('/dashboard/<nickname>/work-orders/add/', methods = ['GET', 'POST'])
@login_required
def work_orders_add(nickname):
ca = check_active(nickname)
if ca[1] == True:
form = AddWorkOrderForm()
u = User.query.get(current_user.id)
c = u.contacts.order_by('name').all()
form.requestor.choices = [(contact, contact.name) for contact in c]
if form.validate_on_submit():
db.session.add(WorkOrder(requestor = form.requestor.data,
date = form.date.data,
notes = form.notes.data,
total = 0.00,
completed = form.completed.data,
user = g.user))
db.session.commit()
return redirect(url_for('work_orders', nickname=current_user.nickname))
elif request.method != "POST":
form.date.data = datetime.date.today()
else: return "didn't work"
return render_template('work_orders_add.html',
user = ca[0],
title = "New Work Order",
form = form)
else: return redirect(url_for('work_orders', nickname=current_user.nickname))
我的forms.py
:
class AddWorkOrderForm(Form)
requestor = SelectField('requestor', coerce=unicode)
date = DateField('date')
notes = TextAreaField('notes')
completed = BooleanField('completed', default = False)
我的models.py
:
class WorkOrder(db.Model):
__tablename__ = 'workorder'
id = db.Column(db.Integer, primary_key = True)
date = db.Column(db.String(64))
notes = db.Column(db.String(1024))
total = db.Column(db.Float)
completed = db.Column(db.Boolean)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
contact_id = db.Column(db.Integer, db.ForeignKey('contact.id'))
items = db.relationship('WorkOrderItem', primaryjoin="WorkOrder.id==WorkOrderItem.work_order_id", backref = 'order')
def __repr__(self):
return '<WorkOrder %r>' % (self.id)
我的HTML文件:
{% extends "_is_logged.html" %}
{% block content %}
<h1>{{ title }}</h1>
<form action="" method="post" name="work_order">
{{ form.hidden_tag() }}
<p>Requestor: {{ form.requestor() }}</p>
<p>Date: {{ form.date() }}</p>
<p>Notes: {{ form.notes(size=70) }}</p>
<p>Completed: {{ form.completed() }}</p>
<p><input type="submit" value="Add Work Order"></p>
</form>
{% endblock %}
感谢。
答案 0 :(得分:0)
我想@Iarissa很久以前就发现了它。表单没有操作值,所以作为第一步,我建议你改变它:
<form action="" method="post" name="work_order">
成:
<form action="{{url_for('work_orders_add')}}" method="POST" name="work_order">
同样根据给出的代码,看起来函数work_orders_add(nickname)
似乎没有正确缩进。 if语句应包含在函数中,以便您具有:
@app.route('/dashboard/<nickname>/work-orders/add/', methods = ['GET', 'POST'])
@login_required
def work_orders_add(nickname):
ca = check_active(nickname)
if ca[1] == True:
form = AddWorkOrderForm()
u = User.query.get(current_user.id)
c = u.contacts.order_by('name').all()
form.requestor.choices = [(contact, contact.name) for contact in c]
if form.validate_on_submit():