Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in
Deleted user
0 / 0 points
Next:
badges earned

Your Points Tracker
Challenges
Leaderboard
  • Global
  • Feed

Badge for your thoughts?

You're enrolled in our new beta rewards program. Join our group to get the inside scoop and share your feedback.

Join group
Recognition
Give the gift of kudos
You have 0 kudos available to give
Who do you want to recognize?
Why do you want to recognize them?
Kudos
Great job appreciating your peers!
Check back soon to give more kudos.

Past Kudos Given
No kudos given
You haven't given any kudos yet. Share the love above and you'll see it here.

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

How to add (append) user in multiuser picker field using jira-python libraries? Edited

Hi Team,

Need help to add a user to the existing multiuser picker field without replacing the original user.

Here is the jira-python code

for issue in jira.search_issues('project = "Abcd" and issuetype = Epic and status not in (Closed) and Testers in (tnaik)', maxResults=200):

print('{}: {}'.format(issue.key, issue.fields.customfield_10600)) //customfield_10600 Testers (multiuser field)

issue.update(fields={"customfield_10600": [ {"name": "tnaik1" }]})

I would like to append tnaik1 where the tnaik exist in the above JQL, Testers field.
The above script completely replaces the user.

Any help would be appreciated.
 
Warm Regards
Tejas

1 answer

1 accepted

0 votes
Answer accepted
Prince Nyeche Community Leader May 11, 2021

You will need to get the accountId for any user picker field, then you can append that. That will involve you searching for the users from your user base.

Hi @Prince Nyeche 

accountID? where do I need to get from?

Is this accountID related from Active Directory?

This is for Jira server.

Prince Nyeche Community Leader May 11, 2021

Hi @Tejas Naik 

Sorry, didn't see the server tags. You don't need accountId if it's server. I believe the  approach I would use here is retrieve the current custom field value in a list, then create a payload that contains the old value and new value, then update the custom field with both values.

 issue.update(fields={"customfield_10600": [ {"name": "tnaik" }, {"name": "tnaik1" }]})

@Prince Nyeche 

Ah-ha!

Here is the problem,

The Testers field contains other users with tnaik.

tester.PNG

In this case, I need to append tnaik1.

@Prince Nyeche 

Can you help me on this

Hey @Tejas Naik 

I will start by get the current issue value. There's this library I wrote called jiraone you can use. Get it by using pip install jiraone.

from jiraone import LOGIN, endpoint, field

user = "username"
password = "password"
link = "https://yourinstance.jira.com"
LOGIN(user=user, password=password, url=link)

keys = "COM-42"
name = "Multiple-User" # custom field name
LOGIN.api = False
issues = LOGIN.get(endpoint.issues(keys)).json()
fields = field.get_field(name).get("id")
value = issues["fields"][fields]

The value will be a list of the current users in the multi user picker field. Then you can append a new value by doing

value.append({"name": "tnaik1"})

issue.update(fields={"customfield_10600": value})

Just to add in, since you're using jira-python library, you just need to get the same login you use to authenticate it and pass it to the LOGIN() variable rather than define a new one.

 

Like Tejas Naik likes this

@Prince Nyeche 

Correct me, if am doing wrong,

Installed pip install jiraone

then

Wrote the code in my sublime and saved it

from jiraone import LOGIN, endpoint, field

user = "tnaik"
password = "xyz123"
link = "https://jiratest.atlassian.info/"
LOGIN(user=user, password=password, url=link)

keys = "ATL-32277"
name = "Testers" # custom field name
LOGIN.api = False
issues = LOGIN.get(endpoint.issues(keys)).json()
fields = field.get_field(name).get("id")
value = issues["fields"][fields]
value.append({"name": "tnaik1"})
issue.update(fields={"customfield_10600": value})

and while trying to run >> python jiratest2.py

Getting Error Like This:

C:\D Drive\Python Practice>python Jiratest2.py
Traceback (most recent call last):
File "Jiratest2.py", line 11, in <module>
issues = LOGIN.get(endpoint.issues(keys)).json()
File "C:\Python\Python38-32\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Anything wrong?

can you remove the "/" from the  link?

Hi @Prince_Service_Rocket ( @Prince Nyeche )

I guess I found another issue, below block shows the error:

C:\D Drive\Python Practice>python jiratest2.py
Traceback (most recent call last):
File "jiratest2.py", line 12, in <module>
fields = field.get_field(name).get("id")
File "C:\Python\Python38-32\lib\site-packages\jiraone\access.py", line 1424, in get_field
"name": a["name"], "id": a["id"], "key": a["key"],
KeyError: 'key'

Prince Nyeche Community Leader May 21, 2021

Hey @Tejas Naik 

The error is saying that the name "key" is not in the payload. Please can you change that line from

fields = field.get_field(name).get("id")

to

fields = field.search_field(name).get("id")

This methods searches for custom fields specifically and doesn't have a "key" name. I don't have a server instance to confirm this but given that Jira is basically the same software across different platform (server or cloud) the response should be similar.

@Prince Nyeche 

No luck still getting an errors

C:\D Drive\Python Practice>python jiratest2.py
Traceback (most recent call last):
File "jiratest2.py", line 12, in <module>
fields = field.search_field(name).get("id")
File "C:\Python\Python38-32\lib\site-packages\jiraone\access.py", line 1393, in search_field
data = load.json()
File "C:\Python\Python38-32\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I was able to append label by using this code

issue.fields.labels.append(u'bla')
issue.update(fields={'labels': issue.fields.labels})

but not sure why I am not able to append user

issue.fields.labels and issue.fields.customfield_10600 are same type class 'list'  

Prince Nyeche Community Leader May 21, 2021

It pretty tricky to debug without knowing what payload comes through with the below

fields = field.search_field(name).get("id")

 Also with this issue.fields.customfield_10600 what is the output you receive. Can you show a sample?

Ok.

issue.fields.customfield_10600.append({"name": "tnaik`"})
issue.update(fields={"customfield_10600": issue.fields.customfield_10600})

The output

 Traceback (most recent call last):
File "jiratest1.py", line 37, in <module>
issue.update(fields={"customfield_10600": issue.fields.customfield_10600})
File "C:\Python\Python38-32\lib\site-packages\jira\resources.py", line 485, in update
super(Issue, self).update(async_=async_, jira=jira, notify=notify, fields=data)
File "C:\Python\Python38-32\lib\site-packages\jira\resources.py", line 225, in update
data = json.dumps(data)
File "C:\Python\Python38-32\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Python\Python38-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python38-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type User is not JSON serializable

Prince Nyeche Community Leader May 21, 2021

@Tejas Naik 

I meant if you could do a print() of issue.fields.customfield_10600 after the append? I want to see the result of that.

Ok,

issue.fields.customfield_10600.append({"name": "tnaik`"})
print(issue.fields.customfield_10600)
#issue.update(fields={"customfield_10600": issue.fields.customfield_10600})

Output:

[<JIRA User: displayName='ravi.kapoor@gtnexus.com', key='rkapoor', name='rkapoor'>, {'name': 'tnaik`'}]

rkapoor already in the Testers field

@Prince Nyeche 

When I use jira.user to append it

testuser = jira.user('tnaik')
issue.fields.customfield_10600.append(testuser)
print(issue.fields.customfield_10600)

The output seems ok, but issue.update was still throwing an error

print()

[<JIRA User: displayName='ravi.kapoor@gtnexus.com', key='rkapoor', name='rkapoor'>, <JIRA User: displayName='Teju Naik', key='tnaik', name='tnaik'>]

issue.update(fields={"customfield_10600": issue.fields.customfield_10600})

Traceback (most recent call last):
File "jiratest1.py", line 38, in <module>
issue.update(fields={"customfield_10600": issue.fields.customfield_10600})
File "C:\Python\Python38-32\lib\site-packages\jira\resources.py", line 485, in update
super(Issue, self).update(async_=async_, jira=jira, notify=notify, fields=data)
File "C:\Python\Python38-32\lib\site-packages\jira\resources.py", line 225, in update
data = json.dumps(data)
File "C:\Python\Python38-32\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Python\Python38-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python38-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type User is not JSON serializable

Prince Nyeche Community Leader May 21, 2021

 @Tejas Naik  please mask your email address. I think the payload might be the problem. You're getting a list but the representation isn't what the issue.update is expecting. You need to get the values in a List[Dict], please can you also print() the value of fields let me see it's value?

fields = field.search_field(name).get("id")

Hi @Prince Nyeche 

Here is my email address tejusn5@gmail.com

And the print of this code is

fields = field.search_field(name).get("id")

SS:

Capture1.PNG 

Thanks

Prince Nyeche Community Leader May 21, 2021

Hey @Tejas Naik 

Can you try this code and let me know what's the value it prints out

keys = "GTN-32231"
name = "Testers"
# get field
issues = LOGIN.get(endpoint.issues(keys)).json()
fields = LOGIN.get("{}/rest/api/2/field".format(LOGIN.base_url)).json()


def rerun():
for z in list(fields):
if name in z["name"]:
return z


d = rerun().get("id")
value: list = issues["fields"][d]
print(value)

Hi @Prince Nyeche 

Some error:

Traceback (most recent call last):
File "jiratest2.py", line 21, in <module>
issues = LOGIN.get(endpoint.issues(keys)).json()
File "C:\Python\Python38-32\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Prince Nyeche Community Leader May 21, 2021

Do the below please and let me know

LOGIN.api = False
keys = "GTN-32231"
name = "Testers"
# get field
issues = LOGIN.get(endpoint.issues(keys)).json()
fields = LOGIN.get("{}/rest/api/2/field".format(LOGIN.base_url)).json()


def rerun():
for z in list(fields):
if name in z["name"]:
return z


d = rerun().get("id")
value: list = issues["fields"][d]
print(value)
Prince Nyeche Community Leader May 21, 2021

@Tejas Naik  Please hide any credentials or remove the image you just posted.

Thanks I forgot to scratch credentials

Prince Nyeche Community Leader May 21, 2021

Let me know the output of my previous comment.

Do the below please and let me know

LOGIN.api = False
keys = "GTN-32231"
name = "Testers"
# get field
issues = LOGIN.get(endpoint.issues(keys)).json()
fields = LOGIN.get("{}/rest/api/2/field".format(LOGIN.base_url)).json()


def rerun():
for z in list(fields):
if name in z["name"]:
return z


d = rerun().get("id")
value: list = issues["fields"][d]
print(value)
from jiraone import LOGIN, endpoint, field

user = "username"
password = "password"
link = "https://yourinstance.jira.com"
LOGIN.api = False
LOGIN(user=user, password=password, url=link)
keys = "GTN-32231"
name = "Testers"
# get field
issues = LOGIN.get(endpoint.issues(keys)).json()
fields = LOGIN.get("{}/rest/api/2/field".format(LOGIN.base_url)).json()


def rerun():
for z in list(fields):
if name in z["name"]:
return z


d = rerun().get("id")
value: list = issues["fields"][d]
print(value)

@Tejas Naikplease ignore my previous comment try the above code as shown and let me know if the output is shown to you. The reason it didn't work before was because on Jira server the endpoint has to be "/rest/api/2" or "/rest/api/latest". The LOGIN.api = False changes that context to latest and has to be called before the login is initiated. That's why the error in JSON always returned "None" denoting that it can't get the right output.

Like Tejas Naik likes this
Prince Nyeche Community Leader May 21, 2021

Okay! That's the payload you need. Now just do the append as before and ensure you add the import from jira-python so you can update the issue (if using that route). otherwise another method you could use to update the issue is

# previous statements
# ...

value.append({"name": "tnaik1"})
# payload to post to edit issue endpoint
data = {
"fields": {d: value}
}
execute = LOGIN.put
(endpoint.issues(keys), payload=data)
print(execute) # should return a type - Response

Hope this helps.

Cheers

Like Tejas Naik likes this

@Prince Nyeche 

Voila! that's awesome.

I need you're another favor that I need to execute by JQL

for issue in jira.search_issues('project = "xyz" and issuetype = Epic and status not in (Closed) and Testers in (tnaik)', maxResults=100):

Where do I need to put the JQL, instead of single issue key? 

Prince Nyeche Community Leader May 21, 2021
# previous import statement
import json

user = "username" password = "password" link = "https://yourinstance.jira.com"
LOGIN.api = False
LOGIN(user=user, password=password, url=link)


jql = "project = 'xyz' and issuetype = Epic and status not in (Closed) and Testers in (tnaik)"

count = 0
while True:
load = LOGIN.get(endpoint.search_issues_jql(query=jql, start_at=count))
if load.status_code < 300:
jira_issue = json.loads(load.content)
if count > jira_issue["total"]:
break
for issue in jira_issue["issues"]:
keys = issue["key"]
name = "Testers"
# other statements goes here.
count += 50

The thing here is that your entire issues will be wrapped in the for loop. So you can do more things from there

Like Tejas Naik likes this

It worked. That's really great @Prince Nyeche .

Prince Nyeche Community Leader May 24, 2021

Great to hear that @Tejas Naik Please accept the answer if the solution answers your question. So other users can use a similar solution.

Hi @Prince Nyeche 

I found a simple way to append user to the multiuser field using jira-python library.

testuser = jira.user('tnaik1')
testlist = issue.fields.customfield_10600
testlist.append(testuser)
new_assignees = [{"name": str(u.name)} for u in testlist] 
issue.update(fields={"customfield_10600": new_assignees})
Like Prince Nyeche likes this
Prince Nyeche Community Leader May 25, 2021

That's great to hear @Tejas Naik .The simpler the better.

Like Tejas Naik likes this

Suggest an answer

Log in or Sign up to answer
TAGS

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you