Is it time for your Django app to sport a shiny favicon?

Read on. It's fairly simple to do.

The first thing that you will need is, well, a favicon. I created tumbling programmer's icon as a SVG, then exported it to png, and renamed the latter as a favicon.ico file. In case you are curious, I used inkscape.

If you haven't done it yet, make sure that Django is setup to serve static files. This tutorial walks you through setting up Django's static directories, and a myriad of other things.

My typical folder setup for a django project is as follows:

|____root_folder
| |____apps
| | |____config
| | | |____(...)
| | |____main
| | | |____(...)
| | |____manage.py
| | |____media
| | | |____twitter48.png
| | |____static
| | | |____css
| | | | |____global.css
| | | |____img
| | | | |____twitter48.png
| | | |____js
| | | | |____global.js
| |____docs
| | |____readme.md
| |____requirements
| | |____(...)

You may choose or already have a different structure. That's OK. In my case, I put the favicon.ico under the .../static/img/ folder.

Once that's done, we need Django to tell most browsers where the app's icon reside . The typical place to do that is in the <head> section of the base.html file, like so:

base.html (based on bootstrap)

{% block bootstrap3_extra_head %}
    ...
    <link rel="icon" href="{% static 'img/favicon.ico' %}">
    ...

The above should do for most browsers. Others will look for the icon by hitting http://www.yourdomain.com/favicon.ico. To cover those, we need to redirect them to http://www.yourdomain.com/static/img/favicon.ico (you may need to edit the .../static/img/... to suit your setup (if different from mine).

We accomplish the redirection by editing our main ulrs.py file and adding the following:

# ... other imports ...
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView

urlpatterns = [ 
    # ... other url patterns ...
    url(r'^favicon.ico$',
        RedirectView.as_view( # the redirecting function
            url=staticfiles_storage.url('img/favicon.ico'), # converts the static directory + our favicon into a URL
            # in my case, the result would be http://www.tumblingprogrammer.com/static/img/favicon.ico
        ),
        name="favicon" # name of our view
    ),
]

That's it. Well, kind of. You can use a favicon checker to verify if your site meets the gazillion use cases that have to be met before it passes with flying colors. You can enter http://www.tumblingprogrammer.com in the favicon checker to see how it scores. It looks like I have more work to do :)

Many thanks to Kristian Glass' article, Failproof Favicons, which shed light on the subject and was the basis for the above approach.