How to serve a static page from.py urls?

Asked

Viewed 113 times

1

I have a website in Django where I want to serve the favicon.ico - which being a static file, is in STATIC_URL/caminho/pro/favicon.ico. It is possible to do this directly from urls.py? (i.e. without having to write a view just for that)

I found that answer in Soen that tells you how to map from one pattern to another [named], but that’s not what I need: I want to map from one pattern to a static URL. Something like:

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

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

P.S. I am using Django 1.4.14, in Python 2.6.0 (and not, due to restrictions in my environment can not update to a newer version...)

  • Why not use {% static 'path' %} in the template?

  • @Orion because it has no template... It is the browser itself that requests the /favicon.ico, regardless of what is on the page (although I recently discovered that it is possible to specify the favicon by a tag on the head page, making this requirement unnecessary)

  • I didn’t even know that the browser requested without indicating on head from the page the icon’s address, so I found it strange not to use the {% static 'path' %}, but it’s explained.

1 answer

1


According to an answer to the same question in Soen, this kind of thing is better done in webserver (Apache, Nginx...) than in Django. However, as a workaround there is the possibility of using one view generic, for example the RedirectView:

from django.views.generic.base import RedirectView

class FaviconView(RedirectView):
    url = "/static/favicon.ico"

urlpatterns = patterns('',
    url(r'^favicon.ico$', FaviconView.as_view()),

Browser other questions tagged

You are not signed in. Login or sign up in order to post.