Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize (override) Flask-Admin's Submit method from edit view

Preconditions:
I'm new to Python and to Flask-Admin in particular. I created a simple test service, which has MondoDB, keeping the data with relationship of 'one-to-one' kind.

employeeName -> salary

The model looks like that:

class Employee(db.Document):
    fullName = db.StringField(max_length=160, unique=True)
    salary = db.IntField()

And I use Flask-Admin to observe the table with the data and to edit it. When I want to change the 'salary' field, I just press the 'edit' button and in Flask-Admin's default edit view I change the integer value. I press 'Submit' and a new value in the database is successfully applied.

Question:
But I need to override the Submit method in the way, that leaves as it is the functionality and adds some custom code. Like let's assume I want to add a comment in the log file after an actual db submit:

logging.warning('The salary of %s: was changed to /%s', fullName, salary)

Any suggestion on how to achieve that would be much appreciated. Perhaps you could direct me in the way to go, since the Flask-Admin documentation doesn't give me enough help so far.

like image 1000
makaron Avatar asked Jan 15 '14 14:01

makaron


2 Answers

You can override on_model_change method to add your custom logic. Check http://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.on_model_change

like image 138
Joes Avatar answered Nov 11 '22 17:11

Joes


I ended up overriding a save method in my Document-derived class. So now my Employee class contains this kind of code:

def save(self, *args, **kwargs):
    print 'whatever I want to do myself is here'
    return super(Employee, self).save(*args, **kwargs)

Today I found that this solution is actually nothing new and is described on StackOverflow.

But for my specific case I think Joes' answer is better. I like it more, because if I override on_model_change I invoke my custom code only if I edit database through Admin webpage; and each programmatic operation over database (like save, update) will work using native code - which is exactly what I want. If I override save method, I will be handling every save operation myself, whether It was initiated by Admin area or programmatically by the server engine.

Solved, thank you!

like image 28
makaron Avatar answered Nov 11 '22 19:11

makaron