首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在django中使用gravatar

在django中使用gravatar
EN

Stack Overflow用户
提问于 2010-11-03 01:16:13
回答 2查看 1.9K关注 0票数 6

我愿意在我的django应用程序中使用gravatars。在应用程序cw中,我创建了一个具有以下体系结构的templatetags目录:

代码语言:javascript
复制
cw/
    templatetags/
         __init.py__
         gravatar.py
    views.py
    ...

gravatar.py包含

代码语言:javascript
复制
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:
        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)

在我尝试过的cw的一个模板中:

代码语言:javascript
复制
{% load gravatar %}

但我得到了:

代码语言:javascript
复制
'gravatar' is not a valid tag library: Template library gravatar not found, tried django.templatetags.gravatar,django.contrib.admin.templatetags.gravatar`

我运行django 1.2.1,Python2.6,在我的settings.py

代码语言:javascript
复制
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",
)

编辑:我找到了另一个更简洁的实现:http://tomatohater.com/2008/08/16/implementing-gravatar-django/

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-03 15:46:07

所以我找到的解决方案是通过创建一个目录,在我的所有应用程序库中共享gravatar模板:

代码语言:javascript
复制
proj/
    __init__.py
    lib/
        __init__.py
        templatetags/
            __init.py__
            common_tags.py

并将lib添加到我安装的应用程序中

票数 2
EN

Stack Overflow用户

发布于 2010-11-07 23:54:34

你的问题在这里:

代码语言:javascript
复制
cw/
    templatetags/
        __init.py__ <<<
        gravatar.py
    views.py
    ...

它应该是__init__.py而不是__init.py__

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4080278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档