Reputation: 9850
In a Django template I have a pinterest style feed, and at the bottom of each block there's an avatar pic.
I'm using the following template tag to show the avatar pic:
{% avatar user 40 %}
def avatar(user, size=80):
if not isinstance(user, User):
try:
user = User.objects.get(username=user)
alt = unicode(user)
url = avatar_url(user, size)
except User.DoesNotExist:
url = AVATAR_DEFAULT_URL
alt = _("Default Avatar")
else:
alt = unicode(user)
url = avatar_url(user, size)
picpath= """<img src="%s" alt="%s" width="%s" height="%s" />""" % (url, alt,
size, size)
return picpath
The problem is that this templatetag makes a call to the database each time to pull out the path to the avatar pic.
Basically what I want to do is only make this call the minimum number of times required (ie. extract the unique users in the current view and only get those pics once)
Is there a way to do this in the template? Or would I have to basically change my view in order to do this?
Upvotes: 0
Views: 50
Reputation: 410942
You probably want to use a cache. You can use template fragment caching to cache the call to the avatar
tag:
{% load cache %}
{# Cache for 60 seconds; you can use any value you want here #}
{% cache 60 avatars %}
{% avatar user 40 %}
{% endcache %}
You can also do caching in the view: either the whole view, or just cache your results. But template caching is probably easiest.
Upvotes: 2