Search code examples
pythonflaskhttp-redirectrequestresponse

Flask render_template does not update the page


I am trying to upload a file, make some calculations to generate an image and then to display it. I came up with the following, but the page does not refresh after the redirect. Even though I get the correct codes:

"POST /result HTTP/1.1" 302 -
"GET /display_image/census_2009b.png HTTP/1.1" 200 -

Not refreshed page

from flask import Flask, request, render_template, send_file, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/result', methods=['GET', 'POST'])
def upload_file():
    file = request.files['file']
    ### generating and saving an image to `filename`...

    return redirect(url_for('display_image', filename=filename))

@app.route('/display_image/<filename>', methods=['GET', 'POST'])
def display_image(filename):
    image_url = url_for('static', filename=filename)
    return render_template('display_image.html', image_url=image_url)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

with index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
        <link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
    </head>
    <body>
        <form action="/result" method="get" class="dropzone" id="my-dropzone"></form>
    </body>
</html>

and display_image.html:

<!DOCTYPE html>
<html>
<head>
    <title>Uploaded Image</title>
</head>
<body>
    <img src="{{ image_url }}" alt="Uploaded image">
</body>
</html>

What am I missing?


Solution

  • Your Flask functions are fine, the issue is with Dropzone. Dropzone controls the upload process, so you have to use Dropzone to redirect once the upload is complete. Check out this post for details on how to redirect with Dropzone.

    I'd also consider implementing Flask Dropzone (made by the guy who answered the question linked above), it has very good documentation.