Apt username asked your question!
You can create a context processor that provides a default avatar for each template and just make sure the context handler caches the image
settings.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 }
Now the template variable 'default_avatar' is available in each template:
{% if usr_avatar %} {{ usr_avatar }} {% else %} {{ default_avatar }} {% endif %}
Or just use the cache in the original request:
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 finally, it would be even better not to leave the default avatar in the database at all, but instead just write a context processor, as described above, but instead of getting the default avatar from the database, just have a static image URL
from django.conf import settings def default_avatar(request): return { 'default_avatar' : '%simages/default_avatar.jpg' % settings.STATIC_URL }
source share