Adding role to a user by code

Hi,
I am trying to add role to user by code . below is my code

def users_roles(self):
	if self.user_rol == "abcr User":
		user = frappe.get_doc("User",self.email)
		user.append('roles',{
					"doctype": "Has Role",
					"role":"abcr User"
					})
		user.save(ignore_permissions=True)

While adding the new password the role automatically get removed for the user.Please help me to fix this .
Thanks

hi @vivin_joseph
This could be because of the self.validate_roles() in the validate method of user.

Try adding the same role in the “Role Profile” also

@ManasSolanki AS you mentioned i have added the same role in Role profile but after saving the user doctype the role removes from the user.below is my code

def users_roles(self):
	if self.user_rol == "abcr User":
		user = frappe.get_doc("User",self.email)
		user.append('roles',{
					"doctype": "Has Role",
					"role":"abcr User"
					})
        user.role_profile_name = self.user_rol
		user.save(ignore_permissions=True)
2 Likes

You have to add the roles in the user profile as well before adding that to the user.

@ManasSolanki After that we have to update password also.

@vivin_joseph this one is worked for me. Thanks