pythonflaskflask-sqlalchemyflask-admin

Flask-Admin set up default user roles when register


I making a dashboard with Flask-Admin and using Flask-SQLAlchemy for my models, like this:

roles_users = db.Table(
    'roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)

class Role(db.Model, RoleMixin):
    __tablename__ = 'role'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

I want when user register with Flask-Admin, the default role for the user has set up to client. enter image description here

I have try something like this on roles column:

roles = db.relationship('Role', secondary=roles_users,
                     backref=db.backref('users', lazy='dynamic'),
                     default='client') # or default=3 (which is '3' is the client id in roles_user association table.

But I got this message:

TypeError: relationship() got an unexpected keyword argument 'default'

And I have also tried this solution But now working for me.

So, is it possible to set default role when user register..?

NOTE: In the other case, I also ask very similar with this question here, but there are in different case. There I want the role are set up when I making a new user by superuser, not when users register by their own.


Solution

  • I modifying @gitter code, so here the worked code for my case:

    @user_registered.connect_via(app)
        def user_registered_sighandler(app, user, confirm_token):
            default_role = Role.query.filter_by(name='client').first()
            user.roles.append(default_role)
            db.session.commit()
    

    Thanks @gitter, you made some insight for me to do it.