I have a website where a user can have multiple roles (usually a user will have multiple roles). What I am trying to do is simply add and remove user roles.
The html side is pretty simple. I have a select 2 multiselect box that loads all the possible users roles. I select or un-select roles and then submit it.
The form simply has 2 variables; username and role(s)
I have a simply for loop with if statements but I appear to be having 2 problems. 1 the if statements are never 'True' for some reason. The 2nd problem is the for loop appears to be exiting it evaluates 1 variable instead of actually looping through all of them.
formroleadmin = AdminUserRoles() # if roles administered
if formroleadmin.roles.data and formroleadmin.validate(): #if form is submitted
# ar = all roles er = existing roles ur = updated roles
allroles = usersRolesNames.query.all() #query all possible roles
usr = formroleadmin.username.data #submitted user name
ur = formroleadmin.roles.data #load the submitted roles
er = usersRoles.query.filter_by(username_fk=usr).all() #get current user roles
for ar in allroles: #loop through all possible roles
if ar in ur: # if the role is a submitted role
if ar not in er: # if role does not exist add it #if role is not assigned
db.session.add(usersRoles(username_fk=usr, role_fk=ar)) #add user
db.session.commit()
elif ar not in ur: # remove it if exists #if not a submitted role
if ar in er: # remove if user is assigned role remove permission
db.session.filter_by(username_fk=usr, role_fk=ar).delete
examples of content
allroles = ['Admin', 'Completions', 'Completions RW', 'Operations'
ur = ['Completions', 'Operations']
so basic sequence I am trying to do is iterate through allroles (ar) and test each value against ur. if the role does or does not exist then it would be added, removed, or passed etc.