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", "")
Related
In views.py VENDOR_MAPPER is list of dictionary each dictionary has id, name, placeholder and autocommit key. I also tried sending json instead of Response object.
resp_object = {}
resp_object['supported_vendors'] = VENDOR_MAPPER
resp_object['vendor_name'] = ""
resp_object['create_vo_entry'] = False
resp_object['generate_signature_flag'] = False
resp_object['branch_flag'] = False
resp_object['trunk_flag'] = False
resp_object['branch_name'] = ""
resp_object['advisory'] = ""
data = {'data': resp_object}
return Response(data)
On home.html I am accessing the vendors_supported which is list and iterate through it, however instead of object i am getting string as type of variable.
var supported_vendors = "{{data.supported_vendors|safe}}";
console.log(supported_vendors);
console.log("Supported_vendors ", supported_vendors);
console.log("Supported_vendors_type:", typeof(supported_vendors));
data.supported_vendors|safe (django template tagging) is used to remove the unwanted characters in the response i have also tried without safe, but still the type was string
also tried converted as well as parse the response but type is shown as string
var supported_vendors = "{{data.supported_vendors}}";
console.log(JSON.parse(supported_vendors));
console.log(JSON.stringify(supported_vendors));
Output generated, i have printed the response type and values i get, also converting using JSON.parse and JSON.stringify did not work and output every time was string
[1]: https://i.stack.imgur.com/DuSMb.png
I want to convert the property into javascript object and perform some computations
You can try this instead ,
return HttpResponse(json.dumps(data),
content_type="application/json")
I got the answer:
var supported_vendors = "{{data.supported_vendors}}";
Converted the above line to
var supported_vendors = {{data.supported_vendors}};
removed quotes from the variable
I'm doing http POST processing of incoming data modifications requests (from a DataTables table) for objects in my Django environment. The POST data comes to me in key=value pairs.
The problem I'm running into is that I haven't found a way to turn this into something I can use. Django objects and modifications are done like this:
id = 123
item = Stuff.objects.get(id=id)
item.title = "New Title"
item.save()
I have the following data attributes:
id = 123
attribute = "title"
value = "New Title"
How can I use them to modify a Django object?
A more efficient way to do this is with:
id = 123
attribute = 'title'
value = 'New Title'
Stuff.objects.filter(id=id).update(**{attribute: value})
This will prevent first fetching the object with a query, and then update it.
If you need to load the object anyway, you can work with setattr(…) [Python-doc]:
id = 123
attribute = 'title'
value = 'New Title'
item = Stuff.objects.get(id=id)
setattr(item, attribute, value)
item.save()
Try using an if statement like
If attribute = 'title'
item.title = value
item.save()
By default delete_item from boto3 does not return an error even if operation is performed on an Item that does not exists.
id = '123'
timenow = '1589046426'
dynamodb = boto3.resource('dynamodb')
boto3_table = dynamodb.Table(MY_TABLE)
response = boto3_table.delete_item(Key={"ID": id, "TIMENOW": timenow})
How do I change the code above to force the delete_item to return an error when item does not exist?
If anyone has the same problem, here is the solution:
response = boto3_table.delete_item(Key={"IDID": idid, "TIMENOW": timenow},
ConditionExpression="attribute_exists(ID) AND attribute_exists(TIMENOW)")
The ConditionExpression parameter with attribute_exists will only delete if the ID and TIMENOW are present in the record.
One way would be to do a conditional delete using a condition-expression on the your partition key attribute name:
response = table.delete_item(
Key={
'pk': "jim.bob",
"sk": "metadata"
},
ConditionExpression="attribute_exists (pk)",
)
If the item exists with this key AND the attribute that is the partition key exists on that key, it deletes the item. If the item does not exist, then you get:
The conditional request failed
Another approach would be to use ReturnValues='ALL_OLD' which returns attributes associated with a given key if they existed prior removal:
response = boto3_table.delete_item(Key={"ID": id, "TIMENOW": timenow}, ReturnValues='ALL_OLD')
if not res['Attributes']:
raise KeyError('Item not found!')
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)
i succesfully retrive objects that i need from a Python ldap query, the result is like this
[('uid=xxxxxx,ou=People,dc=xxxxxxx,dc=eu', {'departmentcode': ['xxxxx']})], [('uid=xxxxxx,ou=People,dc=xxxxxxx,dc=eu', {'departmentcode': ['xxxxx']})]
But from this result, i need just departmentcode. So, How to acess departmentcode value?
Try:
data = [('uid=xxxxxx,ou=People,dc=xxxxxxx,dc=eu', {'departmentcode': ['xxxxx']})], [('uid=xxxxxx,ou=People,dc=xxxxxxx,dc=eu', {'departmentcode': ['xxxxx']})]
departmentcode = []
for elem in data:
departmentcode.append(elem[0][1]['departmentcode'])