我有一个非常简单的表单和表格,我正在尝试使用 python Flask 提交。
sqllite 表由此类创建(这有效):
class Country(db.Model):
__tablename__ = 'countries'
countryid = db.Column(db.Integer, primary_key=True)
country = db.Column(db.String(65), unique=True, index=True)
active = db.Column(db.Boolean, default=True)
def __init__(self, country):
"""
Used to create a Country object in the python server scope
"""
self.country = country
表单是通过这个类生成的:
class CountryForm(Form):
country = StringField('Country name', validators=[Length(0, 64)])
submit = SubmitField('Submit')
页面通过 View 显示:
@main.route('/country', methods=['GET','POST'])
def show_CountryForm():
form = CountryForm()
print 'Form Values',form
if form.validate_on_submit():
ctry = Country(country=form.country.data)
db.session.add(ctry)
flash('The country has been added.')
return redirect(url_for('chinese'))
return render_template("country.html", form=form)
html模板页面是:
{% extends "base.html" %}
{% import "_macros.html" as macros %}
{% block title %}Countries{% endblock %}
{% block page_content %}
<div class="container">
<form method="POST" action="/country">
<div>
<label for="country" class="label_control">
Country
</label>
<div class="form_control" id="country">
{{ form.country }}
</div>
</div>
{{ form.submit() }}
</form>
</div>
{% endblock %}
所以一切似乎都运行正常,没有错误,但记录没有添加到数据库中。任何帮助将不胜感激。
最佳答案
您这里有两个问题。一是您的表单永远不会验证,因为它在任何地方都没有 form.hidden_tag()
并且您没有在页面上显示错误。下面添加了 token 和 div,用于显示出现的任何表单错误。
第二个问题是您永远不会将数据库 session 提交到数据库,因此即使您的表单经过验证,您的数据也不会被保存。
表单未验证且未显示错误:
在您的表单中,尝试添加 {{ form.hidden_tag() }}
,之后您的表单应该可以很好地提交。如果您不添加该内容,表单将引发错误,因为它不再是有效的 XHTML。
<div class="container">
<form method="POST" action="/country">
<div>
<label for="country" class="label_control">
Country
</label>
<div class="form_control" id="country">
{{ form.hidden_tag() }}
{{ form.country }}
</div>
<div class="form_errors">
{{ form.errors }}
</div>
</div>
{{ form.submit() }}
</form>
</div>
<小时/>
数据未保存:
您没有在任何地方调用 db.session.commmit()
,这就是 session
永远不会提交到数据库的原因。
@main.route('/country', methods=['GET','POST'])
def show_CountryForm():
form = CountryForm()
print 'Form Values',form
if form.validate_on_submit():
ctry = Country(country=form.country.data)
db.session.add(ctry)
db.session.commit() # This saves the data.
flash('The country has been added.')
return redirect(url_for('chinese'))
return render_template("country.html", form=form)
关于python - Flask 表单提交不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22854904/