Search code examples
flask-admin

how to use flask-admin for editing modelview


How to set password_hash using generate_password_hash from the edit page of flask-admin

  1. i create a username and password in python shell. the password is hashing
  2. admin.add_view(MyModelView(User, db.session) - let me edit the User class Models
  3. when i edit the password and submit but the password is saved in plain text.

How to edit password from flask-admin, the password should be save in hashing type

My code is:

from werkzeug.security import generate_password_hash, check_password_hash
class User(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     email = db.Column(db.String(120))
     password_hash = db.Column(db.String(64))
     username = db.Column(db.String(64), unique=True, index=True)

     @password.setter
     def password(self, password):
          self.password_hash = generate_password_hash(password)

     def __repr__(self):
          return '<User %r>' % self.username

#Create custom models view
class MyModelView(sqla.ModelView):
    @admin.expose('/login/')
    def index(self):
        return self.render('login.html')

# Create custom admin view
class MyAdminView(admin.BaseView):
    @admin.expose('/')
    def index(self):
        return self.render('myadmin.html')

admin = admin.Admin(name="Simple Views")
admin.add_view(MyAdminView(name='hello'))
admin.add_view(MyModelView(User, db.session))
admin.init_app(app)
app.run()

Solution

  • i solved my problem by using on_model_change function in flask-admin

    #Create custom models view
    class MyModelView(sqla.ModelView):
        @admin.expose('/login/')
        def index(self):
            return self.render('login.html')
        def on_model_change(self, form, User, is_created=False):
            User.password = form.password_hash.data