Skip to content Skip to sidebar Skip to footer

Flask Admin Overrides Password When User Model Is Changed

I am currently diving into a flask project and try to use flask-admin for the first time. Everything is working fine so far, but one thing really bothers me: Whenever I edit my Use

Solution 1:

Might be easier to override the get_edit_form method and delete the password field entirely from the edit form.

classUserView(MyModelView):
    defget_edit_form(self):
        form_class = super(UserView, self).get_edit_form()
        del form_class.password
        return form_class

Another alternative would be to remove the model password field entirely from the form and use a dummy password field that can then be used to populate the model's password. By removing the real password field Flask-Admin will not step on our password data. Example :

classUserView(MyModelView):
    form_excluded_columns = ('password')
    #  Form will now use all the other fields in the model#  Add our own password form field - call it password2
    form_extra_fields = {
        'password2': PasswordField('Password')
    }

    # set the form fields to use
    form_columns = (
        'username',
        'email',
        'first_name',
        'last_name',
        'password2',
        'created_at',
        'active',
        'is_admin',
    )

    defon_model_change(self, form, User, is_created):
        if form.password2.data isnotNone:
            User.set_password(form.password2.data)

Solution 2:

I have faced a similar problem. I needed to generate password's hash when the field of the password had been changed. I did not want to add an additional form for changing the password. On backend I used MongoDB. My solution for flask admin:

class User(db.Document, UserMixin):
    ***
    password = db.StringField(verbose_name='Password')
    roles = db.ListField(db.ReferenceField(Role), default=[] 

    def save(self) -> None:
        if not self.id:
            self.password = hashlib.md5((self.password + Config.SECURITY_PASSWORD_SALT).encode()).hexdigest()
            return super(User, self).save(self)
        else:
            return super(User, self).update(
            ***
            password = self.password,
            )

class UserModelView(ModelView):   
    def on_model_change(self, form, model, is_created):
        user = User.objects(id=model.id)[0]
        if user.password != form.password.data:
            model.password = hashlib.md5((form.password.data + Config.SECURITY_PASSWORD_SALT).encode()).hexdigest()

admin.add_view(UserModelView(User, 'Users'))

For SQL solutions it will be actual as well.

Post a Comment for "Flask Admin Overrides Password When User Model Is Changed"