Flask Admin - Automatically create password hash when creating a new user?

Say I have a user model like:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(255))
    last_name = db.Column(db.String(255))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    registered_on = db.Column(db.DateTime, nullable=True)
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

And an admin view:

class UserView(MyModelView):

    form_columns = (

    form_args = dict(

When I create a new user how to I automatically generate a password hash with something like bcrypt?

2 answers

  • answered 2018-03-13 20:37 Matt Healy

    Could you do something like this; overwrite the init method for the User class and have the password automatically defined?

    class User(db.Model, UserMixin):
        def __init__(self, **kwargs):                                               
            super(User, self).__init__(**kwargs)                                    
            self.password = generate_password() # generate password with bcrypt for example

  • answered 2018-03-13 20:37 spitfiredd

    You can use Flask-Admin's on_model-change and give it logic before it commits to the database.

    from flask_admin.contrib import sqla
    from flask_security import utils
    class UserAdmin(sqla.ModelView):
        def on_model_change(self, form, model, is_created):
            model.password = utils.encrypt_password(model.password)
            # as another example
            if is_created:
                model.registered_on = datetime.now()