i'm willing to use gravatars in my django app.
In the application cw
i created a templatetags
directory with the following architecture:
cw/
templatetags/
__init.py__
gravatar.py
views.py
...
the gravatar.py
contains
from django import template
import urllib, hashlib
register = template.Library()
class GravatarUrlNode(template.Node):
def __init__(self, email):
self.email = template.Variable(email)
def render(self, context):
try:
email = self.email.resolve(context)
except template.VariableDoesNotExist:开发者_C百科
return ''
default = "/site_media/img/defaultavatar.jpg"
size = 40
gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d':default, 's':str(size)})
return gravatar_url
@register.tag
def gravatar_url(parser, token):
try:
tag_name, email = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
return GravatarUrlNode(email)
and in one of the templates of cw
i tried:
{% load gravatar %}
but i get:
'gravatar' is not a valid tag library: Template library gravatar not found, tried django.templatetags.gravatar,django.contrib.admin.templatetags.gravatar`
I run django 1.2.1 python 2.6 and in my settings.py
:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
'django.template.loaders.eggs.load_template_source',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.auth",
"django.core.context_processors.request",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
)
EDIT: i've found this other implementation that is neater: http://tomatohater.com/2008/08/16/implementing-gravatar-django/
Your problem is here:
cw/
templatetags/
__init.py__ <<<
gravatar.py
views.py
...
It should be __init__.py
not __init.py__
So the solution i've found is to share the gravatar templates among all my applications by creating a lib directory:
proj/
__init__.py
lib/
__init__.py
templatetags/
__init.py__
common_tags.py
and adding lib to my installed apps
精彩评论