3

I want to use gravatar on django:

import hashlib
import urllib
from django import template
from django.utils.safestring import mark_safe

register = template.Library()


# return only the URL of the gravatar
# TEMPLATE USE:  {{ email|gravatar_url:150 }}
@register.filter
def gravatar_url(email, size=40):
    default = "https://example.com/static/images/defaultavatar.jpg"
    return "https://www.gravatar.com/avatar/%s?%s" % (
    hashlib.md5(email.lower()).hexdigest(), urllib.urlencode({'d': default, 's': str(size)}))


# return an image tag with the gravatar
# TEMPLATE USE:  {{ email|gravatar:150 }}
@register.filter
def gravatar(email, size=40):
    url = gravatar_url(email, size)
    return mark_safe('<img src="%s" height="%d" width="%d">' % (url, size, size))

I am using this link: Django gravatar

I put this code in a file called 'grav_tag' and load with:

{% load  grav_tag %}

im my template:

{{ user.email|gravatar:150 }}

but I get this error

Unicode-objects must be encoded before hashing
shahab kamali
  • 331
  • 4
  • 16

2 Answers2

5

user.email is a Unicode string, whereas the hash function can only operate on bytes. So you need to convert (i.e. encode) the string into a series of bytes, based on some Unicode character encoding.

Historically, email addresses were restricted to ASCII, but nowadays they can be UTF-8 as well. The gravatar documentation doesn't mention an encoding, so it's not clear if they support UTF-8 email addresses.

The simple answer is just to use email.lower().encode("utf-8"). Since ASCII is the same as UTF-8 throughout the ASCII range, this should work for all email addresses that Gravatar supports.

Community
  • 1
  • 1
Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
2

Are you using Python 3 right now? It because you need to encode your email as utf-8, example email.encode('utf-8'). here'is what I using for my currently project...

import hashlib
from django import template

try:
    # Python 3
    from urllib.parse import urlencode
except ImportError:
    # Python 2
    from urllib import urlencode

register = template.Library()

@register.filter
def gravatar(email, size="75"):
    """
    <img src='{{ request.user.email|gravatar:"75" }}'>
    """
    gravatar_url = "//www.gravatar.com/avatar/" + \
        hashlib.md5(email.encode('utf-8')).hexdigest() + "?"
    gravatar_url += urlencode({'d': 'retro', 's': str(size)})
    return gravatar_url

hope it usefull..

binpy
  • 3,994
  • 3
  • 17
  • 54