1

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?

Jean Jordaan
  • 626
  • 8
  • 24
  • I can't get the uniqueconstraint working, can you please share the syntax if possible, tia. also raised http://stackoverflow.com/questions/30779466/flask-admin-unique-constraint-on-multiple-columns-is-not-working – user2390183 Jun 11 '15 at 11:33

1 Answers1

1

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
            
MBT
  • 21,733
  • 19
  • 84
  • 102
Mensur
  • 1,024
  • 15
  • 24