Search code examples
pythondjangopython-social-auth

How to get user data with python social auth..?


I have created a small project using python social auth for logging with facebook.I have referred python social auth example at link.I can able to get the user name with request.name.But how can i get the other data like first_name,last_name,email.Any help would be appriciated

example code in views is:

def home(request):
   context = RequestContext(request,
                       {'request': request,
                        'user': request.user})
   return render_to_response('home.html',
                         context_instance=context)

Solution

  • Here is one way: request.user has a helper method called is_authenticated, which you can use like this:

    ctx = {
           'user' : request.user
          }
    
    if request.user.is_authenticated():
        ctx.update({
             'first_name': request.user.first_name,
             'last_name': request.user.last_name,
             'email' : request.user.email
        })
    

    Now, the extra attributes are present only if the user is authenticated This is, assuming you are using the auth model of django. If not, please change the model field names accordingly.

    On a side note, you should not be passing the entire request object in the context. You should be extracting only the relevant info and sending it in the context.

    Now, you can access all these values from the template anyways. Example:

    {% if request.user.is_authenticated %}
        {{request.user.username}}
        {{request.user.email}}
        {# etc.. #}
    {% endif %}
    

    No need to send anything in the context explicitly. The request object already has everything