Django Gravatar filter
Posted: December 13th, 2009 | Author: Giv | Filed under: Python, Tutorials | 1 Comment »If you want to add user avatars to your Django app, you can certainly use the excellent django-avatar app. This will let your users upload/edit their own avatars or use Gravatar.
But for my app I only wanted to use Gravatar so I was looking for a simpler solution that let me just pass the user object and an optional size in a template filter and have Gravatar take care of the rest.
The solution is custom template tags. If you’re already used to using the built-in template filters, you’ll know how useful and easy they are. I wanted my Gravatar filter to be as simple as possible. Something like this:
1 | {{ user|gravatar:20 }} |
Where 20 is the optional width/height of the avatar. This would then create an img tag with the full Gravatar URL.
First create your ‘templatetags’ directory and associated files as instructed in the docs. Then create a function that takes in the user object and uses the email address to construct the Gravatar URL:
1 2 3 4 5 6 7 8 9 10 | from django import template import hashlib from django.utils.safestring import mark_safe register = template.Library() @register.filter() def gravatar(user, size=50): gravatar_url = "http://www.gravatar.com/avatar" emailHash = hashlib.md5(user.email.lower()).hexdigest() return mark_safe("<img src='%s/%s.jpg?d=identicon&s=%s' alt='' />" % (gravatar_url, emailHash, size)) |