Search code examples
pythondjangodjango-socialauth

How do I pull information from a field in the admin panel?


I am currently working with Django 1.8 and Python 3. I'm using Python-social-auth to let people sign in via steam id and I'm using the SOCIAL_AUTH_STEAM_EXTRA_DATA = ['player'] setting. In the admin panel you get an field that says Extra Data. And it stores info like this

{"player": {"profileurl": "http://steamcommunity.com/profiles/76561198039465340/", "personaname": "Khailz | Daisuki <3", "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9c/9cce70b919de60669303d057446fbf563221133a_medium.jpg", "steamid": "76561198039465340", "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9c/9cce70b919de60669303d057446fbf563221133a_full.jpg"}}

What I want to do is pull the avatarfull data and put it in my template when a user is logged in.

I have currently tried things like <p>{{ user.get_user_details.avatarfull }}</p> in my login.html and any other combination trying to pull this specific field. I'm not sure how to go about this, how do I pick this field out if it is backend and not in the models.py? I know I'm going about this wrong could someone point me in the right direction?


Solution

  • Untested, but I think the correct path is:

    user.social_auth.get(
        provider='steam'
    ).extra_data.player.avatarfull
    

    Which isn't very convenient, so you might want to add a property to your User object:

    models:

    class MyUser(models.Model):
        # regular stuff
    
        @property
        def get_avatar_url(self):
            try:
                return self.social_auth.get(
                    provider='steam'
                ).extra_data.player.avatarfull
            except (UserSocialAuth.DoesNotExist, AttributeError):
                return 'http://placehold.it/64x64'
    

    templates:

    <img src="{{ user.get_avatar_url }}" />
    

    If you haven't declared a custom user object, you could just as easily create a templatetag or stand alone helper function to retrieve the avatar from an user.

    templatetag:

    @register.filter
    def get_avatar_url(user):
        try:
            return user.social_auth.get(
                provider='steam'
            ).extra_data.player.avatarfull
        except (UserSocialAuth.DoesNotExist, AttributeError):
            return 'http://placehold.it/64x64'
    

    templates:

    <img src="{{ user|get_avatar_url }}" />