views:

37

answers:

1

My site is quite visual and I would like to make use of users avatars all over the site so I think that writing a custom template tag is the best way to go.

My UserProfile is associated with a User and has an profile_pic.

I am making use of django-imagekit and hence the ImageModel comes into play

class UserProfile(ImageModel):  
    profile_pic = models.ImageField(storage=cloudfiles_storage,
                                    upload_to='avatars',
                                    default='avatar-blank.jpg')`

On my front page I am listing news and information that people have posted through calling all my latest posts. and each user is associated with a post.

so in my profiles I have created my templatetags folder and also a file called myavatar_tags.py

in my avatar_tags.py I render the following

from accounts.models import UserProfile  
from imagekit.models import ImageModel  
from django import template 

register = template.Library()

@register.simple_tag  
def my_avatar(request, user):  
    avatar = UserProfile.objects.get(pk=user.id)

my_avatar = register.tag(my_avatar)

Now this is my first tag that I am writing and I am not sure which way to really go with this.

+1  A: 

I think you want an inclusion tag.

@register.inclusion_tag('avatar.html')
def my_avatar(user):
  return {'user': UserProfile.objects.get(pk = user.id) }

Then in a template called avatar.html, write a template for your tag as normal - you probably want something like:

<img src="{{ user.profile_pic.url }}" alt="{{ user.get_name_somehow }}" />

Then you can use this tag like this - given a view which renders this template, passing a User object via the name my_user, and you've put the Python code above in a file called foobar.py.

{% load foobar %}

{% my_avatar my_user %}
Dominic Rodger
hmm, can't seem to get this to work. On my front page I render the posts by making use of the following statement {% for post in posts %} which calls on my post model, in my Post models I have a user field, is all this still applicable then?
ApPeL
@Dominic, I have gotten this to work pretty smooth. I have one question though. I have a message model which has a sender and a recipient. when I pass the recipient, it works. When I pass the sender, it fails, although both of them are user foreignKey fields... Any idea?
ApPeL