1

I have a Django site where I need to serve the favicon.ico - which, being a static file, is at STATIC_URL/path/to/favicon.ico. Is it possible to do so straight from the urls.py? (i.e. without creating a specific view only for that)

I found this question that shows how to map from a pattern to another [named] one, but that's not what I need: I want to map from a pattern to a static URL. Something like:

url(r'^favicon.ico$', view_that_serves_from_STATIC_ROOT_or_redirects_to_STATIC_URL),

Is it possible? And if not, what would be the least laborious way?

P.S. I'm using Django 1.4.14 with Python 2.6.0 (and no, due to constraints in my environment I can't upgrade to a newer version...)

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • 1
    Are you using Apache, nginx or something else? You should try to handle this within that rather than Django. – schillingt Sep 18 '14 at 10:46
  • @schillingt Yes, I can do that! Thanks for your suggestion. Right now I'm just using `runserver` to show a prototype to my customers, but I can postpone it to production if I have to. – mgibsonbr Sep 18 '14 at 11:17

1 Answers1

4

What you are trying to do should be done outside of django. All assets such as CSS, JS, images can reliably be served through something like nginx. I would also recommend that you take a look at django-storage that can help with that. You can read more about how to handle static files in the documentation

That said, you can serve plain templates through urls.py using django's TemplateView. This can be useful if you don't need to make any changes within the template itself. (Works in django 1.4)

Jonathan
  • 8,453
  • 9
  • 51
  • 74
  • I think you're right! I've always used simple `/static/...` to keep things simple, but I know that's not the right way to do it. In this case, however, I'm not linking to a static file within a template, but serving a file with a predefined name (`favicon.ico`; I guess `robots.txt` also falls within that category). I'll check your other sugestion shortly (even if, in production, I leave this to Apache). – mgibsonbr Sep 18 '14 at 11:21
  • Using `TemplateView` didn't work - since my file is a binary one, not a template - but while browsing the link you provided I found `RedirectView`, which solved my problem. Thanks! – mgibsonbr Sep 18 '14 at 11:38
  • TemplateView link is now broken – Andy Swift May 18 '22 at 08:49