Creating avatar using initials in Python with avinit

Sergio Oliveira (seocam)
WhatsGood Dev
Published in
2 min readMar 13, 2017

Recently we decided to change our default place holder avatar to use avatar initials.

For instance, if a user is called “Douglas Adams” the avatar should display the user initials as “DA”.
So, basically we wanted to replace this

by that

At first I thought about using initial.js to do so as it generates really nice avatars, but after thinking a little about it I’ve changed my mind. The reason is simple, our backend currently serves 2 front-ends (and probably will serve more soon) so we definitely don’t want to implement that avatar logic in each UI.

After deciding to implement the avatars in Python I’ve started to look for options that are currently maintained and also supported in Python 3. I’ve came across with django-initial-avatars and also with initials-avatar but none of them matched my requirements.

So, why not implement our own lib?! =)

With that in mind I’ve started checking how each of the 3 libraries (2 Python and 1 Javascript) implemented and the JS implementation was way simpler than the python versions (and generates nicer avatars).

Avinit generates exactly the same SVG avatars than initial.js using a very simple template (as follows):

Avinit is available as open-source (GPL3) in our github account and in PyPI.

To install it using pip just run:

pip install avinit

In the version (1.0) we implemented two functions (avinit.get_svg_avatar(text) and avinit.get_avatar_data_url(text)), both functions receive an text argument, get the first letter of the first and last words and return an avatar. They difference between them it’s only a matter of format: while get_svg_avatar returns an string with the SVG XML get_avatar_data_urlreturns a formated data URL which can be used directly into the <img src=""> tag.

Follows an usage example:

Avinit has no dependencies and it’s quite simple to use as you can see.
Patches and welcome so please create a fork and submit your Pull Requests!

This was initially published at Crave's Dev Blog in 2016–08–22.

--

--