1

I'm trying to show a confirmation/success message to the user in my Flask app, but I can't figure out how to display it in a modal.

@app.route("/", methods=["POST"]
def sendForm():
    form = ContactForm(request.form)
    if request.method == 'POST':
        if form.validate():
            # do stuff with form data
            return render_template("contact.html", form=form)
        else:
            # display error message
    else:
        return render_template("index.html")

The part where I return the contact.html template is where I need help, I think. Because that page is basically refreshed and shown again after the POST request successfully completes. Need to display a confirm message to the user in a modal instead.

On the front-end, my form is looks like this:

<form method="POST" action="{{ url_for('sendForm') }}">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
    {{ render_field(form.email) }}
    {{ render_field(form.name) }}
    <input id="submit-form" type="submit" value="Send">
</form>
kaoscify
  • 1,743
  • 7
  • 37
  • 74

1 Answers1

4

I would do some form of this...

Pass a boolean in your render_template:

submission_successful = True #or False. you can determine this.
render_template("contact.html", form=form, submission_successful=submission_successful))

Then in your template place an if statement

{% if submission_successful %}
    // modal elements here
{% endif %}
Phillip Martin
  • 1,910
  • 15
  • 30
  • 1
    This is an awesome approach. Very simple too, thank you! One thing I've noticed is that when my form goes through, the browser URL is updated with `@app.route("/")`. Clicking on the refresh icon in the browser resends the `POST` request. Is there a way to avoid this? – kaoscify Apr 26 '16 at 18:38
  • That is actually an interesting question. At first glance I think this might help - http://stackoverflow.com/questions/4327236/stop-browsers-asking-to-resend-form-data-on-refresh – Phillip Martin Apr 26 '16 at 18:42
  • Thank you! Will check it out. – kaoscify Apr 26 '16 at 18:51