Read time: 2 minutes

Get user data using django-social-auth

August 2018: Please note that this post was written for an old version of Django. It is left here for historical purposes only.

Recently we had to add support for social networks login to an application we are developing and we chose django-social-auth to work with. It is a well documented and easy to use django application for authentication.

But we wanted to do more than just authenticating the user, we wanted to get extra data like the profile picture, gender, etc. Fortunately django-social-auth has an useful pipeline that you can expand to fulfill this kind of tasks. I will explain briefly how to achieve this. I will assume you already have authentication working which is very well explained in the documentation.

First of all, we should define the pipeline in our like this:

All the items in the pipeline except the last one are from django-social-auth and are part of the original pipeline, and the last one is the one in charge of getting the avatar and should be coded.

After we have our pipeline ready we need to implement the function that looks like this:

def get_user_avatar(backend, details, response, social_user, uid,
                    user, *args, **kwargs):
    url = None
    if backend.__class__ == FacebookBackend:
        url = "" % response['id']

    elif backend.__class__ == TwitterBackend:
        url = response.get('profile_image_url', '').replace('_normal', '')

    if url:
        profile = user.get_profile()
        avatar = urlopen(url).read()
        fout = open(filepath, "wb") #filepath is where to save the image
        fout.close() = url_to_image # depends on where you saved it

If you want to extend the functionality of getting the avatar from others social networks you should check the backend and get the image url accordingly.

On the other hand, if you want to get another kind of information like gender or age you should define another pipeline item and do something like we did above.

That’s pretty much everything. Happy coding!

Like what you read?

Subscribe to our newsletter and get updates on Deep Learning, NLP, Computer Vision & Python.

No spam, ever. We'll never share your email address and you can opt out at any time.
Comments powered by Disqus

Get in touch

Do you have a project in mind?
We'd love to e-meet you!

Thanks for reaching out!

We'll reply as soon as possible.

And in the meantime?
Check out our blog to see what we're currently working on.