Flask admin overrides password when user model is changed

one*_*iro 5 python flask flask-admin

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 User model the users password gets overwritten. I am following the advice given in the second answer of this question to prevent flask-admin from re-hashing my password. Unfortunately the emptied password field still gets written to the database.

我试图从User-Model那里获取当前密码,该密码作为on_model_change方法的参数,但是在某种程度上该密码似乎已经被覆盖(或者这不是我在这里查看的实际数据库模型-我是有点困惑)。

这是我的代码:

用户模型

class User(UserMixin, SurrogatePK, Model):
    """A user of the app."""

    __tablename__ = 'users'
    username = Column(db.String(80), unique=True, nullable=False)
    email = Column(db.String(80), unique=True, nullable=False)
    #: The hashed password
    password = Column(db.String(128), nullable=True)
    created_at = Column(db.DateTime, nullable=False,
                        default=datetime.datetime.utcnow)
    first_name = Column(db.String(30), nullable=True)
    last_name = Column(db.String(30), nullable=True)
    active = Column(db.Boolean(), default=False)
    is_admin = Column(db.Boolean(), default=False)

    def __init__(self, username="", email="", password=None, **kwargs):
        """Create instance."""
        db.Model.__init__(self, username=username, email=email, **kwargs)
        if password:
            self.set_password(password)
        else:
            self.password = None

    def __str__(self):
        """String representation of the user. Shows the users email address."""
        return self.email

    def set_password(self, password):
        """Set password"""
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, value):
        """Check password."""
        return bcrypt.check_password_hash(self.password, value)

    def get_id(self):
        """Return the email address to satisfy Flask-Login's requirements"""
        return self.id

    @property
    def full_name(self):
        """Full user name."""
        return "{0} {1}".format(self.first_name, self.last_name)

    @property
    def is_active(self):
        """Active or non active user (required by flask-login)"""
        return self.active

    @property
    def is_authenticated(self):
        """Return True if the user is authenticated."""
         if isinstance(self, AnonymousUserMixin):
            return False
        else:
            return True

    @property
    def is_anonymous(self):
        """False, as anonymous users aren't supported."""
        return False
Run Code Online (Sandbox Code Playgroud)

Flask-Admin UserView

class UserView(MyModelView):
    """Flask user model view."""
    create_modal = True
    edit_modal = True

    def on_model_change(self, form, User, is_created):
        if form.password.data is not None:
            User.set_password(form.password.data)
        else:
           del form.password

    def on_form_prefill(self, form, id):
        form.password.data = ''                                              
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助。提前致谢,

奥尼罗

pjc*_*ham 8

覆盖该get_edit_form方法并完全从编辑表单中删除密码字段可能更容易。

class UserView(MyModelView):
    def get_edit_form(self):
        form_class = super(UserView, self).get_edit_form()
        del form_class.password
        return form_class
Run Code Online (Sandbox Code Playgroud)

另一种替代方法是从表单中完全删除模型密码字段,并使用可用于填充模型密码的虚拟密码字段。通过删除真实密码字段,Flask-Admin 不会踩到我们的密码数据。例子 :

class UserView(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',
    )

    def on_model_change(self, form, User, is_created):
        if form.password2.data is not None:
            User.set_password(form.password2.data)
Run Code Online (Sandbox Code Playgroud)