I have a flask application where the user has to upload a file, then some operation happens on it and the result is displayed.
The restriction on file size is 2 MB. For this, I have used
app.config['MAX_CONTENT_LENGTH'] = 2 * 1000 * 1000
There is errorhandler function in flask to display custom error messages...
@app.errorhandler(413)
def page_not_found(e):
return "File should be less than 2 MB"
But it is displayed on a new page.
I want the error to be displayed on the same page so that user can try with a new file. As it is now, to upload a new file the user has to press the back button to switch back to the previous page and then upload the file.
Is there a way to do this? Like, using 'flash' or something else?
CodePudding user response:
Using flash is possible. First, flash your message and then render the template.
@app.errorhandler(413)
def page_not_found(e):
flash("File should be less than 2 MB")
return render_template('myPage.html')
In your html, use Jinja:
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="popup">
<div class="text-center">
<script>window.alert('{{ messages[0] }}')</script>
</div>
</div>
{% endif %}
{% endwith %}