您提问的用户名!
http://blog.madpython.com/204/07/django-context-processors-best-practice/“rel=“nofollow”>context processor,为每个模板提供违约ava,并且简单地确保背景处理者 ca照图像
http://www.py。
TEMPLATE_CONTEXT_PROCESSORS = (
...
myapp.context_processors.default_avatar ,
...
)
myapp/context_processors.py
from django.core.cache import cache
def default_avatar(request):
default_avatar = cache.get( default_avatar , False)
if not default_avatar:
default_avatar = UsrAvatar.object.get(id= 0 )
return {
default_avatar : default_avatar
}
现在,每个模板都有可变的缺漏_:
{% if usr_avatar %}
{{ usr_avatar }}
{% else %}
{{ default_avatar }}
{% endif %}
替代 在你最初的询问中公正地使用切身:
try:
usr_avatar = UsrAvatar.objects.get(user=request.user.id)
except UsrAvatar.DoesNotExist:
usr_avatar = cache.get( default_avatar , False)
if not usr_avatar:
usr_avatar = UsrAvatar.objects.get(id= 0 )
But 最后,甚至最好避免将违约ava留在数据库中,而只写上上文提到的背景处理器,而不要从亚洲开发银行获得违约ava,而只是静态的ur。
from django.conf import settings
def default_avatar(request):
return {
default_avatar : %simages/default_avatar.jpg % settings.STATIC_URL
}