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

1

6

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
Joelie answered 13/12, 2015 at 13:50 Comment(0)
M
9

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

Marcelmarcela answered 14/12, 2015 at 15:1 Comment(2)
@ pjcunningham: The answer is working well, and would you please advise how to model.user_roles = current_user.roles. I want to get the current user's role, thanks.Hemostat
Wow.., thank you very much @pjcunningham, You saved my time a lot :)Diaphysis

© 2022 - 2024 — McMap. All rights reserved.