mirror of
https://github.com/jazzband/django-avatar.git
synced 2026-03-16 22:20:30 +00:00
Allow provider to override template_name and context
Also an example provider which renders the user's initals against a randomly colored background.
This commit is contained in:
parent
e5d488a08d
commit
0e87dc2f82
3 changed files with 44 additions and 2 deletions
|
|
@ -82,3 +82,26 @@ class FacebookAvatarProvider(object):
|
|||
fb_id=fb_id,
|
||||
size=size
|
||||
)
|
||||
|
||||
|
||||
class InitialsAvatarProvider:
|
||||
"""
|
||||
Returns a tuple with template_name and context for rendering the given user's avatar as their
|
||||
initials in white against a background with random hue based on their primary key.
|
||||
"""
|
||||
|
||||
def get_avatar_url(user, size):
|
||||
initials = user.first_name[:1] + user.last_name[:1]
|
||||
if not initials:
|
||||
initials = user.username[:1]
|
||||
initials = initials.upper()
|
||||
context = {
|
||||
'fontsize': (size*1.1)/2,
|
||||
'initials': initials,
|
||||
'hue': user.pk % 360,
|
||||
'saturation': '65%',
|
||||
'lightness': '60%',
|
||||
}
|
||||
return ('avatar/initials.html', context)
|
||||
|
||||
|
||||
|
|
|
|||
12
avatar/templates/avatar/initials.html
Normal file
12
avatar/templates/avatar/initials.html
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<span style='background-color: hsla({{ hue }}, {{ saturation }}, {{ lightness }}, 1);
|
||||
width: {{ size }}px;
|
||||
height: {{ size }}px;
|
||||
font-size: {{ fontsize }}px;
|
||||
text-align: center;
|
||||
color: white;
|
||||
display: inline-block;
|
||||
line-height: {{ size }}px;
|
||||
{{ kwargs.style }}'
|
||||
{% for key, value in kwargs.items %}{% if key != 'style' %}{{ key }}="{{ value }}" {% endif %}{% endfor %}>
|
||||
{{ initials }}</span>
|
||||
|
||||
|
|
@ -44,12 +44,19 @@ def avatar(user, size=settings.AVATAR_DEFAULT_SIZE, **kwargs):
|
|||
url = avatar_url(user, size)
|
||||
context = {
|
||||
'user': user,
|
||||
'url': url,
|
||||
'alt': alt,
|
||||
'size': size,
|
||||
'kwargs': kwargs,
|
||||
}
|
||||
return render_to_string('avatar/avatar_tag.html', context)
|
||||
template_name = 'avatar/avatar_tag.html'
|
||||
ext_context = None
|
||||
try:
|
||||
template_name, ext_context = url
|
||||
except ValueError:
|
||||
context['url'] = url
|
||||
if ext_context:
|
||||
context = dict(context, **ext_context)
|
||||
return render_to_string(template_name, context)
|
||||
|
||||
|
||||
@register.filter
|
||||
|
|
|
|||
Loading…
Reference in a new issue