How to set password_hash using generate_password_hash from the edit page of flask-admin
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()
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',
),
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With