0
votes

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"}}]

2
You're looking up a dictionary, shouldn't it be print obj[0]['pk']?Austin Phillips

2 Answers

3
votes

You got your types wrong:

  • obj is a list
  • obj[0] is a dict
  • a dict has no pk attribute, however you can retrieve the value for key "pk" with: obj[0]['pk']
2
votes

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:

  1. You generate the JSON object server side.
  2. JSON-encode it. You now have a unicode string.
  3. JSON-encode it again. Now you have a unicode string as a JSON object.

  4. Retrieve it from the URL.

  5. Decode it once. You now have the unicode string which encodes the object.
  6. Extract 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': ...