Search code examples
djangodjango-urlsdjango-staticfiles

How can I serve a static page from urls.py?


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...)


Solution

  • 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)