[英]Flask redirect using url_for with parameter
I'm trying redirect the function to herself, but changing the value of a parameter.我正在尝试将函数重定向到她自己,但更改了参数的值。
This is my code:这是我的代码:
@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)
I would like that when redirecting, the save variable would be True, but it is always False.我希望在重定向时,保存变量为 True,但始终为 False。
In the form code I have this:在表单代码中,我有这个:
{% if save %}
<script type="text/javascript"> alert("Saved!");</script>
{% endif %}
Use the default values in route:在路由中使用默认值:
@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)
I found an alternative solution我找到了一个替代解决方案
I changed it:我改变了它:
return redirect(url_for('index', save=True))
for this one对于这个
return render_template('form.html', form=form, save=True)
It will make a new render它将进行新的渲染
and I added this in the form.html code我在 form.html 代码中添加了这个
$(document).ready(function() {
$('input').val("");
});
this solves my problem, and the reason is that I have a confirmation message (when save is True) and the fields are cleared这解决了我的问题,原因是我有一条确认消息(当 save 为 True 时)并且字段被清除
but if someone really needs a return redirect url_for
can use Suman Niroula's solution without problems但如果有人真的需要return redirect url_for
可以毫无问题地使用 Suman Niroula 的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.