# HG changeset patch # User Brian Neal # Date 1298340686 0 # Node ID a1bf6cf4972002c526597c2fef7cd9eb2e4fa4a3 # Parent 5453aedf95fda8787f0e6af1f6ba7e4a8b2e092c Modified the implementation of the avatar tag to look for an attribute 'user_profile' on the user object. If present, this is assumed to be the profile. This improves the performance of the member list and some forum views. diff -r 5453aedf95fd -r a1bf6cf49720 gpp/bio/templatetags/avatar_tags.py --- a/gpp/bio/templatetags/avatar_tags.py Sun Feb 20 22:12:06 2011 +0000 +++ b/gpp/bio/templatetags/avatar_tags.py Tue Feb 22 02:11:26 2011 +0000 @@ -1,34 +1,60 @@ """ -Template tags for the bio application. +Template tags for the bio application. """ from django import template from django.conf import settings from django.core.cache import cache +from bio.models import UserProfile + + register = template.Library() +def get_img_info(profile=None): + """ + This function returns a 3-tuple: (url, width, height) for a user profile + avatar. If the profile is None or the profile doesn't contain a valid + avatar, info for the default avatar is returned. + + """ + if profile is None or profile.avatar.name == '': + return (settings.AVATAR_DEFAULT_URL, + settings.MAX_AVATAR_SIZE_PIXELS, + settings.MAX_AVATAR_SIZE_PIXELS) + else: + return (profile.avatar.url, + profile.avatar.width, + profile.avatar.height) + + @register.simple_tag def avatar(user, align='bottom'): - """Returns the HTML for a user's avatar image.""" + """ + Returns the HTML for a user's avatar image. - # In the cache is stored a tuple containing info about the - # avatar: (url, width, height) - cache_key = 'avatar_' + user.username - img_info = cache.get(cache_key) - if img_info is None: - try: - profile = user.get_profile() - except: - profile = None - if profile is None or profile.avatar.name == '': - img_info = (settings.AVATAR_DEFAULT_URL, - settings.MAX_AVATAR_SIZE_PIXELS, - settings.MAX_AVATAR_SIZE_PIXELS) - else: - img_info = (profile.avatar.url, profile.avatar.width, - profile.avatar.height) - cache.set(cache_key, img_info) + If the user object has an attribute 'user_profile', this is assumed to be + the user's profile that has been pre-fetched. Otherwise, the cache is + consulted to retrieve the avatar info for the user. If there is a cache + miss, only then will a get_profile() call be made. + """ + # img_info is a tuple that contains info about the avatar: + # (url, width, height) + + if hasattr(user, 'user_profile'): + img_info = get_img_info(user.user_profile) + else: + # try the cache + cache_key = 'avatar_' + user.username + img_info = cache.get(cache_key) + if img_info is None: + try: + profile = user.get_profile() + except UserProfile.DoesNotExist: + profile = None + + img_info = get_img_info(profile) + cache.set(cache_key, img_info) alt = user.username title = alt