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.
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..
- [Django]-Django: get_perm(permision_string)
- [Django]-How to return all records but exclude the last item