I'm studying Flask-Admin combined with PeeWee Backend ModelView (but my question may be applied to SQLAlchemy backend too), and there are two things I could not find in the docs or examples:
(1). When I my model has an unique field and I test/try to duplicate it, I get a default Flask crash screen, with the message: "IntegrityError: column username is not unique"
I'm testing the PeeWee example available in https://github.com/mrjoes/flask-admin/blob/master/examples/peewee/simple.py, and I changed line 21 to "username = peewee.CharField(max_length=80, unique=True)"
Then I try to add two users with "username" = "user1".
Is there a polite way to get back to the edit screen (or even the list screen, any admin screen would do) but with a controlled error message? I don't need a custom error message, current message is ok (IntegrityError: column username is not unique). But I don't wan't the crash screen.
I could setup/use Flask's default 500 page, but then I would exit completelly the Flask-Admin flow and the user would "miss" the data he just typed.
I would like to get back to the edit screen, but with some sort of alert/error message. I don't mind to have to extend the templates, this is not a problem. But I could not find a place to intercept the error and handle it properly. Any suggestions?
and (2):
I also need a way to add some pre-save validation in the flow. For example, I'm in an edit form of an entity that has initial_date and final_date, and I want to make sure final_date is greater than initial_date or is null, before save.
I could do this client-side, via javascript, extending the edit template for that entity and adding my validation script in the tail block (and intercepting the form.submit event).
But what if my validation demands some server-side last-minute validation? Is there any way / place to intercept the flow and add my validation, and with luck, throw back my error message, in the same fashion discussed in question 1?
thanks in advance,
regards,
on_model_change
- you can throw exception from there. While exception will be shown with Werkzeug debugger, in production mode you'll see nice error message. – Oron_model_change
is a post-save hook as noted in documentation": "Perform some actions after a model is created or updated." There is no pre-save hook in Flask admin AFAIK. So extending the base form class and customization in sub class is the only way to answer OP's question. – Teelon_model_change
is called when model was updated with form data, but before session was committed to the database. So throwing exception there would prevent any changes to be applied. – Or