Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use flask-admin for editing modelview

Tags:

flask-admin

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()
like image 987
Do Nguyen Ha Avatar asked Dec 03 '22 17:12

Do Nguyen Ha


2 Answers

Alternative solution is to subclass a TextField adding custom processing logic:

class MyPassField(TextField):
    def process_data(self, value):
        self.data = ''  # even if password is already set, don't show hash here
        # or else it will be double-hashed on save
        self.orig_hash = value

    def process_formdata(self, valuelist):
        value = ''
        if valuelist:
            value = valuelist[0]
        if value:
            self.data = generate_password_hash(value)
        else:
            self.data = self.orig_hash

class UserView(ModelView):
    form_overrides = dict(
        passhash=MyPassField,
    )
    form_widget_args = dict(
        passhash=dict(
            placeholder='Enter new password here to change password',
        ),
    )
like image 168
MarSoft Avatar answered Jun 01 '23 20:06

MarSoft


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
like image 22
Do Nguyen Ha Avatar answered Jun 01 '23 22:06

Do Nguyen Ha