Search code examples
djangodjango-templatesdjango-imagekitdjango-custom-tags

django avatar custom template tag


My site is quite visual and I would like to make use of users avatars all over the site so I think that writing a custom template tag is the best way to go.

My UserProfile is associated with a User and has an profile_pic.

I am making use of django-imagekit and hence the ImageModel comes into play

class UserProfile(ImageModel):  
    profile_pic = models.ImageField(storage=cloudfiles_storage,
                                    upload_to='avatars',
                                    default='avatar-blank.jpg')`

On my front page I am listing news and information that people have posted through calling all my latest posts. and each user is associated with a post.

so in my profiles I have created my templatetags folder and also a file called myavatar_tags.py

in my avatar_tags.py I render the following

from accounts.models import UserProfile  
from imagekit.models import ImageModel  
from django import template 

register = template.Library()

@register.simple_tag  
def my_avatar(request, user):  
    avatar = UserProfile.objects.get(pk=user.id)

my_avatar = register.tag(my_avatar)

Now this is my first tag that I am writing and I am not sure which way to really go with this.


Solution

  • I think you want an inclusion tag.

    @register.inclusion_tag('avatar.html')
    def my_avatar(user):
      return {'user': UserProfile.objects.get(pk = user.id) }
    

    Then in a template called avatar.html, write a template for your tag as normal - you probably want something like:

    <img src="{{ user.profile_pic.url }}" alt="{{ user.get_name_somehow }}" />
    

    Then you can use this tag like this - given a view which renders this template, passing a User object via the name my_user, and you've put the Python code above in a file called foobar.py.

    {% load foobar %}
    
    {% my_avatar my_user %}