sharataka
sharataka

Reputation: 5132

How do I access the token generated using django's social auth?

I am using django's social_auth for facebook authentication. I am trying to access the token once a user is logged in using facebook so the app can do things like retrieve the user's friends and what is on his/her newsfeed. However, I am having trouble getting that token. Below is what I have. {{instance}} displays in the template but when I add {{token}} I get an error saying 'QuerySet' object has no attribute 'tokens'. How do I get the generated token?

view

def friends(request):   
    instance = UserSocialAuth.objects.filter(user=request.user).filter(provider='facebook') 
    token = instance.tokens
    return render_to_response('reserve/templates/friends.html', {'token':token, 'instance':instance},
        context_instance=RequestContext(request))

template

{{instance}}
<br>
{{token}}

Upvotes: 2

Views: 3170

Answers (1)

mgibsonbr
mgibsonbr

Reputation: 22007

The error says it all: a QuerySet is a collection of whatever your searched for (in this case, UserSocialAuth). To get a field in that model you need to iterate over the collection:

tokens = [x.tokens for x in instance]

As an alternative, if you're sure your filter will return exactly one instance (not zero, not 2 or more) you can use get instead of filter:

instance = UserSocialAuth.objects.get(user=request.user, provider='facebook') 
token = instance.tokens

Note however that a single provider can return more than one token, like oauth_token and oauth_token_secret, so you should select which one you want and/or format it appropriately.

Upvotes: 2

Related Questions