Flask_WTF / Python:执行HTML POST时,init值变为None



我正在做一个快速项目来训练我的Python/Flask/Flask_WTF技能。不幸的是,我花了2天时间没有理解代码的行为和不同的值。

这里是简化的代码(所有模块加载),为您提供更好的可见性。

  • 注意:MovieDB是继承自db的类。model (SQLAlchemy)使用不同的键(这里没有问题)
  • (MAIN.PY)

@app.route("/")
def home():
##### Test init of DB to check above is correct
if not Path("instance/movies.db").exists():
print("OK")
db_test_init()
##### End of test init
return render_template("index.html", DB=MovieDB.query.filter_by().all())

问题出在下面的路由中。

@app.route("/edit", methods=["GET", "POST"])
def edit():
movie_id = request.args.get("id")
movie_edit = MovieDB.query.get(movie_id)
print(movie_id, movie_edit)
form_edit = EditForm()  # creating a form object (here 2 fields and a submit button)
if form_edit.validate_on_submit():  # if button is pushed
print(movie_id, MovieDB.query.get(movie_id))
# movie_to_edit.rating = form_edit.rating.data
# movie_to_edit.review = form_edit.review.data
db.session.commit()
return redirect(url_for("home"))
return render_template("edit.html", movie=movie_edit, form=form_edit)

[EDIT.HTML]

{% block content %}
<div class="content">
<h1 class="heading">{{ movie.title }}</h1>
<p class="description">Edit Movie Rating</p>
<form action="{{ url_for('edit') }}" method="POST">
{{ form.csrf_token }}
{{ render_form(form, button_style='btn btn-outline-dark btn-lg') }}
<input type='hidden' name="id" value="{{ movie.id }}" />
</form>
</div>
{% endblock %}

现在在"编辑"中发生了什么?路线:

  • 如果我使用GET

第一次打印返回:1 <= =比;好的

  • 如果我使用POST(在表单中提交按钮)

第一次打印现在返回:None None第二次打印返回:None None

为什么第一次打印甚至在进入语句之前就得到了不同的值if form_edit.validate_on_submit():

request.args包含可选的查询参数,在URL后面附加一个问号。通常用于GET请求,如搜索查询。

http://localhost:5000/edit?arg0=0&arg1=1

如果您使用url_for在表单的action属性中输入URL而没有设置id属性,则该URL将不包含在request.args中。因此,两个值都返回None
id传递给url_for,这将被附加到url。

url_for('edit', id=movie.id)

有了变量规则,就有可能在URL中假定id

@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
# your code here
如上所述,您可以将movie.id分配给url_for中的id属性,这将集成到URL的路径中。
在我看来,最明智的方式是将id传输到服务器。

request.form包含表单数据,可以以与request.args相同的方式使用。但是,隐藏的输入字段在端点内被忽略。但是传输数据是另一种可能的选择。

还有request对象的其他属性可以用于其他目的,例如传输文件或接收JSON格式的数据。

最新更新