Super Simple Django Gravatar

June 30, 2016 in Django


Before turning to a django package for a new feature, it's sometimes a good idea to take a step back and look at how difficult it would actually be to do it yourself. Sometimes its easier to implement yourself rather than install a package for something simple. I noticed this with gravatar.

Gravatar is a service for globally recognized avatars. Many times this is used in sites so that we don't have to store users' images. Today we'll run through how to implement a simple template tag to do this

First let's look at the what we want the template to look like. We want it to be something like this, meaning that we want a 50x50 image of the user's gravatar.

{% load app_tags %}
<img src="{{ user|gravatar:50 }}" />

Implementing this is actually really simple! Let's create a file at app/templatetags/app_tags.py and add this tag.

from hashlib import md5
from django import template

register = template.Library()


@register.filter(name='gravatar')
def gravatar(user, size=35):
    email = str(user.email.strip().lower()).encode('utf-8')
    email_hash = md5(email).hexdigest()
    url = "//www.gravatar.com/avatar/{0}?s={1}&d=identicon&r=PG"
    return url.format(email_hash, size)

Boom. That was simple! Now you have gravatars for any user