Search code examples
pythonflaskflask-sqlalchemyflask-admin

How to enforce constraints in `flask-admin`?


We're using http://flask-admin.readthedocs.org/ for a quick admin interface. Our model has constraints defined as follows:

__table_args__ = (
        db.UniqueConstraint(user_id, role, domain_id),
        db.UniqueConstraint(user_id, role, customer_id),
        )

When saving a record that violates a constraint while in debug mode, the app stops with a traceback. If not in debug mode, it reports the error in a flash message and rolls back the transaction.

This is the desired behaviour (i.e. flash message and rollback). The user did something wrong and was protected from entering bad data: it's not an error that should show a traceback.

What is the proper Flask way of handling such exceptions elegantly? Should I be overriding the {create,update,delete}_model methods of ModelView?


Solution

  • You can implement the on_model_change and on_model_delete functions. So you can check if the data is unique and give a more user friendly message in case a constraint is not satisfied. Here is an example of checking some constraints before the delete/insert/update operation

    class ExampleView(ModelView):
        def on_model_delete(self, model):
            #check constraint
                
    
        def on_model_change(self, form, model, is_created):
            #insert 
            if is_created:
                #check constraint
            #update
            else:
                #check constraint