Custom Tag to Render Avatar in Django Userena

Here is a simple custom tag to render a users avatar (‘mugshot’) when using Django Userena. It optionally takes width and or height in pixels.

Place the following code in /templatetags/my_app_tags.py:

your_app/
    models.py
    templatetags/
        __init__.py
        my_app_tags.py


from django import template
register = template.Library()

from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def avatar(context, height=None, width=None):
    """ returns html for avatar, optional height/width supplied """
    user = context['user']
    widthAttr = 'width="%s"'%width if width is not None else ""
    heightAttr = 'height="%s"'%height if height is not None else ""
    return """<img %s %s class="avatar" src="%s"" alt="avatar image"  />"""%(heightAttr, widthAttr, user.get_profile().get_mugshot_url())

The following template shows how this could be used


{% load myapp_tags %}

{% avatar %}
{% avatar height=5 %}
{% avatar width=150 %}
{% avatar width=100 height=100 %} 
 

This entry was posted in Django, Python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>