Reputation: 11
I have search every where but no one stated this error before.
The obj will return a unicode object but it will return the following error
Exception Type: AttributeError
Exception Value:'unicode' object has no attribute 'pk'
It works if I hard code the result from the response.
CustomerAccount.py
from django.contrib.auth.models import User
check login
return user
api.py
result = CustomerAccount.login(username, password)
return HttpResponse(json.dumps(result), content_type="application/json")
views.py
import urllib2
import json
res = urllib2.urlopen("http://127.0.0.1:8000/api/login?username=admin&password=admin").read()
obj = json.loads(res)
print obj[0].pk
Result of print obj:
[{"pk": 1, "model": "auth.user", "fields": {"username": "admin", "first_name": "Admin", "last_name": "admin", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2013-05-29T08:08:43.859Z", "groups": [], "user_permissions": [], "password": "pbkdf2_sha256$10000$1HdCOPgsoXvx$8jjOpTFVcVAtUshpjJDPEGs/TRq7jeJ2T/2i55FIPeM=", "email": "[email protected]", "date_joined": "2013-05-15T07:59:30Z"}}]
Upvotes: 0
Views: 1796
Reputation: 57453
You say you get
Exception Value:'unicode' object has no attribute 'pk'
when retrieving obj[0].pk
. If it was a data type error, you would get 'dict' object has no attribute 'pk'
instead.
So the problem is that your obj[0]
is not a dict
as you expect, or a list
, but it is a unicode string.
As per comments, this is what happens:
JSON-encode it again. Now you have a unicode string as a JSON object.
Retrieve it from the URL.
pk
from the unicode string... and you can't do that.A quick fix would be to decode the object twice. The real fix is detect where the double encoding takes place and prevent that from happening.
The telltale that should have told me what had happened was this:
[{"pk": 1, "model": ...
If that had been a Python object (instead of a JSON encoding), it would have been:
[{u'pk': 1, u'model': ...
Upvotes: 2
Reputation: 76835
You got your types wrong:
obj
is a list
obj[0]
is a dict
dict
has no pk
attribute, however you can retrieve the value for key "pk"
with: obj[0]['pk']
Upvotes: 3