Search code examples
pythonflask-sqlalchemyflask-admin

Flask-Admin / Flask-SQLAlchemy: set user_id = current_user for INSERT


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

Solution

  • In your admin view for the Apikey model you need to do a couple of things; hide the user_id field and manually set the user_id before the form's data gets posted to the database.

    Assuming you're using Flask-Login or Flask-Security too, your view class should look something like:

    class ApikeyView(sqla.ModelView):
    
        form_excluded_columns = ('user_id')
    
        def on_model_change(self, form, model, is_created):
    
            if is_created:
                model.user_id = current_user.id
    

    Don't forget to import current_user from flask.ext.login