django.utils.datastructures.MultiValueDictKeyError: "'user_data'"
Is what i get when trying to access user_data from the request.POST
post_data = dict(request.POST)
print(post_items)
returns
{'user_data[first_name]': ['Jamie'], 'user_data[name_last]': ['Lannister'], 'campus': ['McHale Hall'], 'user_data[twitter]': ['#jamielan']}
So if I try to get just the user_data, I try this (doesn't work)
post_data = dict(request.POST)
user_data = post_data['user_data']
I just want to get all instances of user_data in this dict and store as json. How can I do that?
Expected out put would be something like
Your POST data is really weird but for the sake of correctness, you should do:
first_name = post_data["user_data[first_name]"]
name_last = post_data["user_data[name_last]"]
Because the string user_data[first_name] is the key for the dict not just string user_data.
Edit:
If you want to convert user data into dict, you should loop on request.POST and check for keys that contains user_data keyword:
user_data = {}
for key, value in request.POST.iteritems():
if 'user_data' in key:
field = key.split('[')[1].replace(']', '')
user_data[key] = value
# convert into json
json_user_data = json.dumps(user_data)
Related
I'm trying to serialize the form objects and return to the AJAX call so that I can display them in the template, but I'm not able to serialize them unlike serializing the model objects don't we have an option for form objects
if request.method == 'POST':
temp_data_form = TemplateDataForm(request.POST)
if request.POST.get('temp_id'):
# getting id of the current template
existing_template = Template.objects.filter(id=request.POST.get('temp_id'))[0]
if request.POST.get('item'):
item_query = existing_template.tempdata_set.filter(item=request.POST.get('item'))
if item_query:
item_query = item_query[0] and True
# we only edit the existing object of the template always as we create the object by default on GET request
if existing_template and existing_template.title != request.POST.get('title') and request.POST.get('title')!= None:
existing_template.title = request.POST.get('title')
existing_template.save()
if temp_data_form.is_valid() and item_query != True:
# Template items alias data
td_obj = temp_data_form.save(commit=False)
td_obj.template = existing_template
td_obj.save()
values_form = []
for item in existing_template.tempdata_set.all():
values_form.append(TemplateDataForm(instance=item))
return JsonResponse(values_form, safe=False)
I'm getting the below error.
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type TemplateDataForm is not JSON serializable
Assuming your TemplateDataForm is a Django form, it should have a "cleaned_data" attribute. You need to serialize that data and not the form itself. So for a single form, that would look like the below. Also, cleaned_data is a dictionary, so you can drop the "safe=False" argument.
return JsonResponse(values_form.cleaned_data, safe=False)
However, based on your code, it looks like you are trying to loop through a child object set or multiple forms. So, for that, you would probably want to pre-build the json dictionary response in the loop.
json_response_dict = {}
for item in existing_template.tempdata_set.all():
values_form.append(TemplateDataForm(instance=item))
# Add to your response dictionary here. Assuming you are using
# django forms and each one is a valid form. Your key will
# need to be unique for each loop, so replace 'key' with a
# loop counter such as 'form' + counter or maybe a form instance
# cleaned_data pk. If looping through child set objects, then
# reference the appropriate attribute such as values_form.title.
json_response_dict['key'] = values_form.cleaned_data
return JsonResponse(json_response_dict, safe=False)
Then in javascript, for your response, you would need to access each key.
$.ajax({
method: 'POST',
url: yourURL,
data: yourData
}).always(function (response) {
/* Test viewing the title for a single object in dictionary. Otherwise, loop
* through the response in each dictionary subset to get the keys/values.
*/
alert(response.title);
});
I am getting JIRA data using the following python code,
how do I store the response for more than one key (my example shows only one KEY but in general I get lot of data) and print only the values corresponding to total,key, customfield_12830, summary
import requests
import json
import logging
import datetime
import base64
import urllib
serverURL = 'https://jira-stability-tools.company.com/jira'
user = 'username'
password = 'password'
query = 'project = PROJECTNAME AND "Build Info" ~ BUILDNAME AND assignee=ASSIGNEENAME'
jql = '/rest/api/2/search?jql=%s' % urllib.quote(query)
response = requests.get(serverURL + jql,verify=False,auth=(user, password))
print response.json()
response.json() OUTPUT:-
http://pastebin.com/h8R4QMgB
From the the link you pasted to pastebin and from the json that I saw, its a you issues as list containing key, fields(which holds custom fields), self, id, expand.
You can simply iterate through this response and extract values for keys you want. You can go like.
data = response.json()
issues = data.get('issues', list())
x = list()
for issue in issues:
temp = {
'key': issue['key'],
'customfield': issue['fields']['customfield_12830'],
'total': issue['fields']['progress']['total']
}
x.append(temp)
print(x)
x is list of dictionaries containing the data for fields you mentioned. Let me know if I have been unclear somewhere or what I have given is not what you are looking for.
PS: It is always advisable to use dict.get('keyname', None) to get values as you can always put a default value if key is not found. For this solution I didn't do it as I just wanted to provide approach.
Update: In the comments you(OP) mentioned that it gives attributerror.Try this code
data = response.json()
issues = data.get('issues', list())
x = list()
for issue in issues:
temp = dict()
key = issue.get('key', None)
if key:
temp['key'] = key
fields = issue.get('fields', None)
if fields:
customfield = fields.get('customfield_12830', None)
temp['customfield'] = customfield
progress = fields.get('progress', None)
if progress:
total = progress.get('total', None)
temp['total'] = total
x.append(temp)
print(x)
I have the following code, and it works. I am checking if a JSON object has a full field and does not contain the underlying fields (Jira API, if you're interested). Is there a more concise way of writing the for loop?
myResponse = requests.get(url,auth=(urlUser,urlPass))
jd = myResponse.json()
myVals = jd['issues']
print(myVals[0].keys())
for issue in myVals:
if issue['fields']['assignee'] is not None:
assignee = issue['fields']['assignee']['displayName']
else:
assignee = "Unassigned"
You can use dict.get with fallback dictionary:
>>> issues = {'fields': {'assignee': None}}
>>> issues['fields']['assignee'] or {} # fallback to an empty dictionary
{}
>>> (issues['fields']['assignee'] or {}).get('displayName', 'Unassigned')
'Unassigned'
for issue in myVals:
assignee = (issue['fields']['assignee'] or {}).get('displayName', 'Unassigned')
OR define fallback dictionary like below:
UNASSIGNED = {'displayName': 'Unassigned'}
for issue in myVals:
assignee = (issue['fields']['assignee'] or UNASSIGNED)['displayName']
I have a dictionary object namely person.json:
def get_web_parent(self, pk, is_ajax=False):
try:
person = models.Person.objects.active.get(pk=pk)
description = person.json
person.json is returning a dictionary like {dict}{'description':'example'}
How do I access description value.
I tried person.json.description but no luck.
you can use person.json.get("description", <<other value if key is missing>>)
assuming you get a Dict object.
If person.json is a JSON string you might need to use
person_dict = json.loads(person.json)
and then access it as
person_dict.get("description", "")
Suppose in my python below function, i am getting the json feeds like below
def mapper_1(self, key, line):
j_feed = json.loads(line)
unicoded = j_feed[u'category_description'].encode("utf-8")
cn = j_feed[u'categoryname']
location = j_feed[u'location']
How to check if there is any blank fields for data in categoryname/categorydescription/location from the input.json.
Say you are unsure of your fields, you can use .get and provide it a default sentinel value
fields = ['categoryname', 'categorydescription', 'location']
for field in fields:
print j_feed.get(field, "not set!")