User.add_roles(role) didn't work probably

Well when i try to add a role to specific user using python it didn’t appened the role to that specific user

def sync_delegation_roles(delegation_name):

    """Grant active delegation roles and remove roles when the delegation ends."""

delegation = frappe.get_doc("Delegation", delegation_name)

delegatee = frappe.get_doc("User", delegation.delegatee)

roles = {row.document_type for row in delegation.allowed_doctypes if row.document_type}




if delegation.active and getdate(delegation.from_date) <= getdate(nowdate()) <= getdate(

delegation.to_date

    ):

current_roles = set(frappe.get_roles(delegatee.name))

print("Current Roles:", current_roles)

for row in delegation.allowed_doctypes:

if row.document_type and row.document_type not in current_roles:

row.db_set("role_was_present", 0, update_modified=False)

delegatee.flags.ignore_permissions = True

for role in roles:

if role not in current_roles:

delegatee.add_roles(role)

print(f"Added role {role} to {delegatee.name}")

# delegatee.add_roles(*sorted(roles))

delegatee.reload()

frappe.db.commit()




print("Roles Added:", sorted(roles))

current_roles_ = set(frappe.get_roles(delegatee.name))

print("Current Roles final :", current_roles_)

return

this is the snippet code i used to handle the process i tried to track the issue nothing helped ? Any Hint Guys !!

This problem might be occurring if the target user already has a Role Profile assigned to them.

In Frappe’s core user.py file (frappe/core/doctype/user/user.py), there is a method called populate_role_profile_roles that runs inside validate() on every save. This method automatically overwrites all of the user’s roles with only the roles defined in their assigned Role Profile. I’m not sure if this is fully intended or by design, but it wipes out any ad-hoc roles added programmatically via add_roles().

As a workaround, you might want to remove the Role Profile from the user first before assigning roles directly to them.

Hi @Hussam_al-maswari ,

Frappe’s add_roles() method is working perfectly in my case. There can be multiple reasons why the role is not being added, so I would first verify that the function is actually being called and that all the conditions required for adding the role are being met.

As an alternative approach, you can also add the role directly to the User’s roles child table:

user_doc = frappe.get_doc("User", "[email protected]")
user_doc.append("roles", {"role": "Website Customer"})
user_doc.save()

You can replace the User and Role values according to your use case.

I would also recommend adding some logging/debugging around the function call and the conditions to confirm whether the role-assignment block is actually being reached.

actually ,I figured it out that was the issue i had , thanks brother anyway :slight_smile: