[英]Jinja template has no hidden tags and validate_on_submit not working
我正在尝试制作一个天气应用程序。我正在使用 flask。我收到以下错误:
jinja2.exceptions.UndefinedError: 'forms.WeatherForm object' has no attribute 'hidden_tag'
我的代码如下:
天气.html
{% extends 'layout.html' %}
{% block content %}
<form method="POST" action="" autocomplete="off">
<!-- {{ form.hidden_tag() }} -->
<fieldset class="form-group">
<legend class="border-bottom mb-4">Place</legend>
<div class="form-group">
{{ form.place.label(class="form-control-label") }}
{% if form.place.errors %}
{{ form.place(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.place.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.place(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
{% endblock content %}
路线.py:
from flask import (render_template, url_for, flash,
redirect, request, Flask)
from forms import WeatherForm
app = Flask(__name__)
@app.route("/")
@app.route("/home")
def home():
return render_template('home.html')
@app.route('/weather', methods=['GET', 'POST'])
def weather():
form = WeatherForm()
# if form.validate_on_submit():
# return redirect('url_for("result")')
return render_template('weather.html', form=form)
@app.route('/result',methods=['POST'])
def result():
render_template('result.html')
if __name__ == '__main__':
app.run(debug=True)
我已经评论了 if 语句 bcz 我收到另一个错误...
AttributeError: 'WeatherForm' object has no attribute 'validate_on_submit'
forms.py:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class WeatherForm():
place = StringField('Place', validators=[DataRequired()])
submit = SubmitField('Post')
不确定我是否没有为上述错误导入一些功能。我是 flask 的新手......谢谢你的帮助
编辑:找到另一个解决方案..如果 csrf 不起作用,我们可以设置一个 SECRT_KEY... 另一个在我第一次出错后有帮助的答案
考虑FlaskForm
实现到您的WeatherForm
中:
class WeatherForm(FlaskForm):
place = StringField('Place', validators=[DataRequired()])
submit = SubmitField('Post')
此外,在应用程序上实施CSRF 保护:
from flask_wtf.csrf import CSRFProtect
# Add this somewhere in your app's initialization
csrf = CSRFProtect(app)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.