turbo-flask: Flask `flash` not working with Turbo
I stumbled upon flash not working when using turbo.
controller:
@route("/delete/<id>", methods=["POST"])
def delete(self, id):
if self.measurement.is_used:
flash("You can not delete this!")
return redirect(url_for("MeasurementsView:index"))
If I remove turbo from page head, flash is working. If turbo is in, it’s not (rest of the code is working no problem).
I can imagine replacing flash mechanism with turbo-stream in future (it would be neat actually), but not sure what to do now.
If I understand correctly, it’s because turbo turns my redirect to fetch, and flash is not rerendered. So I need to force flash element reloading. Not sure how tho.
(Also, the flash message is rendered next time page is “properly” reloaded.)
Thanks for your help!
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 15 (13 by maintainers)
@janmpeterka this is something that I think would be hard to generalize, but in your own application you can add an after_request handler that checks for a turbo stream response and in that case appends the rendered alert as an additional section in the stream.
That’s not what I’m saying. If you have a turbo frame for the content area of your page, then including the alerts inside this frame will resolve the issue completely, without you having to do anything differently.
If including the alerts in the turbo frame isn’t feasible, then the solution I’m showing in the example linked above, which pushes the update directly to the alert section is also fairly straightforward.
What case(s) aren’t covered by the two solutions I proposed? The whole point of turbo.js is avoiding the use of JS, so why would you resort to a JS solution when there are no-JS solution available to you?
I have now added a small example in this repo that shows how to flash a message in a turbo-stream response. It is actually simpler then the code shown above. https://github.com/miguelgrinberg/turbo-flask/tree/main/examples/flash
@tnaescher I tried that, but for some reason I wasn’t able to make it run correctly 😦 No time now (exams ahead), I will probably look into it later (~ in two weeks).
Here’s my WIP code:
I also stumbled on a thing I don’t understand - elements in
response.responselist (turbo streams) are sometimesstringand sometimesbytestype. Not sure if it matters, just weird for me.