ERPNext Foundation ERPNext Cloud Chat Blog Discuss Frappé* Donate

Adding role to a user by code

customization

#1

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


#2

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


Add user roles programatically
#4

@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)

#5

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


#6

@ManasSolanki After that we have to update password also.