Using Flask-Admin + Flask-SQLAlchemy I have defined three models: User, Apikey, Exchange.
When an authenticated user creates a new Apikey through the web admin interface I'd like that the user_id on this new row that's inserted in the database is set to the current user_id that is logged in.
With my current implementation the user can choose any user she likes (which is not desired).
This is my definition of the models:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(255))
last_name = db.Column(db.String(255))
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
apikeys = db.relationship('Apikey', backref='user')
def __str__(self):
return self.email
class Apikey(db.Model):
id = db.Column(db.Integer, primary_key=True)
exch_user = db.Column(db.String(255))
exch_pass = db.Column(db.String(255))
exch_key = db.Column(db.String(255))
exch_secret = db.Column(db.String(255))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
exch_id = db.Column(db.Integer, db.ForeignKey('exchange.id'))
class Exchange(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
apikeys = db.relationship('Apikey', backref='exchange')
def __str__(self):
return self.name
model.user_roles = current_user.roles
. I want to get the current user's role, thanks. – Hemostat