使用带有参数的url_for进行烧瓶重定向

时间:2020-02-27 13:59:18

标签: python flask flask-wtforms wtforms

我正在尝试将函数重定向到自己,但是更改了参数的值。

这是我的代码:

@app.route('/', methods=["GET", "POST"])
def index(save=False):
    form = FormFields()
    if form.validate_on_submit:
        csv = Csv(form)
        csv.savecsv()
        return redirect(url_for('index', save=True))
    else:
        print(form.errors)
    return render_template('form.html', form=form, save=save)

我希望重定向时, save 变量为True,但始终为False。

在表单代码中,我有这个:

{% if save %}
    <script type="text/javascript"> alert("Saved!");</script>
{% endif %}

2 个答案:

答案 0 :(得分:0)

在路由中使用默认值:

    @app.route('/', methods=["GET", "POST"], defaults={'save': False})
    @app.route('/<save>', methods=["GET", "POST"])
    def index(save):
        form = FormFields()
        if form.validate_on_submit:
            csv = Csv(form)
            csv.savecsv()
            return redirect(url_for('index', save=True))
        else:
            print(form.errors)
        return render_template('form.html', form=form, save=save)

答案 1 :(得分:0)

我找到了替代解决方案

我更改了:

return redirect(url_for('index', save=True))

为此

return render_template('form.html', form=form, save=True)

它将制作新的渲染

然后我在form.html代码中添加了它

$(document).ready(function() {
    $('input').val("");
});

这解决了我的问题,原因是我收到确认消息(当保存为True时)并且字段被清除

但是如果某人真的需要return redirect url_for 可以毫无问题地使用Suman Niroula的解决方案