我正在尝试制作天气应用程序..
我正在使用烧瓶。
我收到以下错误:
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 %}
route.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')
不确定我是否没有为上述错误导入一些功能.. 我是烧瓶新手...感谢您的帮助
编辑:找到另一个解决方案..如果 csrf 不起作用,我们可以设置一个 SECRT_KEY... Another answer that helps after my first error
答案 0 :(得分:0)
考虑在您的 FlaskForm
中实现 WeatherForm
:
class WeatherForm(FlaskForm):
place = StringField('Place', validators=[DataRequired()])
submit = SubmitField('Post')
此外,在应用上实现 CSRF protection:
from flask_wtf.csrf import CSRFProtect
# Add this somewhere in your app's initialization
csrf = CSRFProtect(app)