[英]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.