Setup a favicon.ico in Django

Up until a couple weeks ago, I had never installed a FavIcon on any of my Django sites. I never really thought about it until one day I enabled the SEND_BROKEN_LINK_EMAILS setting for one of my sites. As soon as I did that, I was able to track down links to broken pages very quickly. It also notified me that I didn't have a favicon.ico file setup anywhere on my site, and there are a great many programs out there that look for this file automatically.

At first I tried to go through Apache to get this working, but I'm no Apache guru so I was less than successful in taking this route. A couple of days ago I figured out a little trick to make the missing favicon.ico file stop sending me "broken link" e-mails hundreds of times a day. The solution? Put a favicon on my site, of course!

The approach I took was to simple add some information to my main urls.py file. Here's the line straight from my URLconf:

(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/images/favicon.ico'}),

Hah! Simple isn't it? This way Apache is still handling the actual serving of the static image file--Django just handles the redirect. Ever since I added this line to my URLconf, I've not received one "broken link" e-mail pertaining to the missing favicon.ico file. That leads me to believe that most applications can understand the redirect and plug the actual image file where it belongs.

Oh, and for those of you who might be curious... My favicon.ico is actually just a PNG image that I renamed to favicon.ico. Again, most things seem to understand this (but I could be wrong).

See below for a more complete example of my URLconf

from django.conf.urls.defaults import *

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'^robots\.txt$', 'django.views.generic.simple.direct_to_template', {'template': 'robots.txt', 'mimetype': 'text/plain'}),
    (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/images/favicon.ico'}),
    (r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'base_home.html'}),
)

Comments

Comments powered by Disqus