python - Flask Web Development 第四章 Web表单 为什么要用form.name.data = ''
伊谢尔伦
伊谢尔伦 2017-04-17 16:04:59
0
1
678
@app.route('/', methods=['GET', 'POST']) 
def index():
    name = None
    form = NameForm()
    if form.validate_on_submit():
        name = form.name.data
        form.name.data = ''
    return render_template('index.html', form=form, name=name)
    

在if语句中,这个form.name.data被赋值给局部变量name且表单域的数据属性通过赋值为空字符串而被清除。

问题一:
在上述代码中,为什么需要清除form.name.data

问题二:

如下代码,为什么使用session的时候,就不需要清空form.name.data?

from flask import Flask, render_template, session, redirect, url_for

@app.route('/', methods=['GET', 'POST']) 
def index():
    form = NameForm()
    if form.validate_on_submit():
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))
    
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
左手右手慢动作

Pay attention to the specific meaning of the code. If you use a decorator to add routes in flask, you need to determine the http method.
In the first piece of code, there is no explicit judgment whether it is the get or post method, so the default is the get method. When the get method is requested, form.validate_on_submit() will not be verified, so the returned page name value is empty (None). When you use the post method to submit a form, if the verification passes, then the name is equal to the submitted value. As for why you need to clear the value of form.name.data, it is because if you do not clear it, the form in the page returned after submission The name value will remain what you filled in before. The second paragraph has been verified and used a redirect page, so it doesn’t matter if it’s not clear, it has nothing to do with the session

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template