Search code examples
pythonflaskflask-wtformswtforms

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.

In the form code I have this:

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

Solution

  • 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

    $(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

    but if someone really needs a return redirect url_for can use Suman Niroula's solution without problems