开发者

django avatar custom template tag

开发者 https://www.devze.com 2023-01-12 05:23 出处:网络
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 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.mode开发者_开发百科ls 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.


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 %}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号