Search code examples
pythonflaskflask-sqlalchemyflask-admin

flask-admin: How to get current user's other info(besides id, name, email)?


I want the user's name and his team are stored automatically when creating a project. The classes are defined below:

class Team(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)

    def __str__(self):
       return self.name  

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)
    teams = db.relationship('Team', secondary=teams_users,uselist=False,
                        backref=db.backref('users', lazy='dynamic'))

    def __str__(self):
       return self.first_name

 class Project(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    team = db.Column(db.Unicode(64))
    developer = db.Column(db.Unicode(128))  

       def __unicode__(self):
          return self.developer

And I use the following to store the current user's first name and team when a project is created:

     class ProjectView(sqla.ModelView):
        def on_model_change(self, form, model, is_created):
           if is_created:
             model.developer = current_user.first_name
             model.team = current_user.teams

the user name is correctly saved but the teams was failed to saved. I've also tried to store model.team =current_user.email , model.team =current_user.last_name and model.team =current_user.idand all worked. Not sure what happened why failed to store current_user.teams. Thanks.


Solution

  • because User.teams is a not a db.Column, like Project.team and the other fields, its a db.relationship, if you want to assign a value to it, it has to be an instance of Team

    so you would have to do something like:

    class ProjectView(sqla.ModelView):
        def on_model_change(self, form, model, is_created):
            if is_created:
                model.developer = current_user.first_name
                model.team = Team(name=current_user.teams)