简体   繁体   中英

How to interact with individual form fields in Flask-Admin?

How can I iterate over certain form fields available in Flask-Admin?

Usually, I use flask_bcrypt to hash passwords when a user submits one of the custom forms I created for the website. But if I change a particular user's password with flask-admin , it just won't work because it does not save the new password as a hash.

I want to hash the new password before storing it in the database.

How can I achieve this goal? I've looked online but found nothing. So is it simply not possible? I've tried looking at the docs but couldn't really find anything useful there.

Let's say this is my data model:

class User(db.Model , UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)

And this is my register route that I would normally use if I don't use flask-admin :

@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_pass=bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user = User(username=form.username.data,email=form.email.data, password=hashed_pass)
        db.session.add(user)
        db.session.commit()

I'd like to get the password field from the admin model view and do the same as the code mentioned above.

I've found a way to work around this issue while looking at the SQLAlchemy docs simply set up an event listener that kicks in whenever a password value is edited or changed.

@event.listens_for(User.password, 'set')
def hashPass(target, value, oldvalue, initiator):
    if value != oldvalue:
        return bcrypt.generate_password_hash(value).decode('utf-8')
    else: 
        return oldvalue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM