Have a custom primary key for users.id in flask-security

Issue

I want to have a custom key for the field id, for example, id_user, I’ve tried the following

class UserModel(db.model, UserMixin)
...
        @property
        def id(self):
            return self.id_user

But couldn’t make it work. When I try to login it sends me this message:

{
"message": "You don't have the permission to access the requested resource. It is either read-protected or not readable by the server."
}

Solution

I ended up with a nasty solution. I cloned the UserModel object, added a duplicated field for id, with the custom key I needed and told Flask-Security to use that object as the UserModel This is the function code I used:

def clone_model(model):
data = model
attr = getattr(model, "id_user")
setattr(data, "id", attr)
return data

cUserModel = clone_model(UserModel)
user_datastore = SQLAlchemyUserDatastore(db, cUserModel, Roles)

security = Security(app, user_datastore)

Hope someone find it useful

Answered By – Hugo Pablo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published