1

this is my code :

def callback(req):
 token = req.session.get('token', None)
 if not token:
  return render_to_response('callback.html', {
   'token': True
  })
 token = oauth.OAuthToken.from_string(token)
 if token.key != req.GET.get('oauth_token', 'no-token'):
  return render_to_response('callback.html', {
   'mismatch': True
  })
 token = get_authorized_token(token)

 # Actually login
 obj = is_authorized(token)
 if obj is None:
  return render_to_response('callback.html', {
   'username': True
  })
 try: user = User.objects.get(username=obj['screen_name'])
 except: user = User(username=obj['screen_name'])

 user.oauth_token = token.key
 user.oauth_token_secret = token.secret
 user.save()
 req.session['user_id'] = user.id
 del req.session['token']

 s = ''.join('%s: %s </br>' % (a, getattr(user, a)) for a in dir(user))
 return HttpResponse(s)

and i want use

s = ''.join('%s: %s </br>' % (a, getattr(user, a)) for a in dir(user))
return HttpResponse(s)

to show the user's properties ,

but i get a error :

AttributeError at /twitter/login/callback/

Manager isn't accessible via User instances

so what can i do ,

thanks

zjm1126
  • 34,604
  • 53
  • 121
  • 166

2 Answers2

1

You should troubleshoot by using a for loop and finding out where the problem is!

I looped through the User object, and found it doesn't like getattr(user, '_base_manager') or getattr(user, 'objects')

Do you just want the fields, or really all of the python code associated with the user object?

If you just want the fields defined in models.py:

for field in user._Meta.fields:
    print '%s: %s' % (field.name, field.value_to_string(user))

if you want all the magic that dir does
Just do a normal for loop. List comprehensions are not going to catch exceptions any easier.

for attr in dir(user):
    try:
        print '%s: %s' % (attr, getattr(user, attr))
    except Exception, e:
        print '%s: %s' % (attr, e)

If you love your list comprehensions that much

def no_exception_getattr(user, attr):
    try: 
        return getattr(user, attr)
    except Exception, e: 
        return e

''.join(['%s: %s' % (x, no_exception_getattr(user, x)) for x in dir(user)])
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
0

A cleaner way would be to add an introspective method to your model.

see Django templates: loop through and print all available properties of an object?

and also Iterate over model instance field names and values in template

Community
  • 1
  • 1
Kenny Shen
  • 4,773
  • 3
  • 21
  • 18