我只想把favicon。ico放到我的staticfiles目录中,然后让它显示在我的应用程序中。

我怎样才能做到呢?

我已经把favicon.ico文件放在我的staticfiles目录中,但它没有显示,我在日志中看到了这一点:

127.0.0.1 - - [21/Feb/2014 10:10:53] "GET /favicon.ico HTTP/1.1" 404 -

如果我去http://localhost:8000/static/favicon.ico,我可以看到图标。


当前回答

一个轻量级的技巧是在你的urls.py文件中做一个重定向,例如添加一个这样的视图:

from django.views.generic.base import RedirectView

favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)

urlpatterns = [
    ...
    re_path(r'^favicon\.ico$', favicon_view),
    ...
]

当你真的没有其他静态内容要托管时,这是一个让favicons工作的简单技巧。

其他回答

在模板文件中

{% load static %}

然后在<head>标签内

<link rel="shortcut icon" href="{%  static 'favicon.ico' %}">

这假设您已经在settings.py中适当配置了静态文件。


注意:旧版本的Django使用load staticfiles,而不是load static。

如果你允许的话

Alias /favicon.ico /var/www/aktel/workspace1/PyBot/PyBot/static/favicon.ico

为虚拟主机添加别名。(在apache配置文件中)类似于robots.txt

Alias /robots.txt /var/www/---your path ---/PyBot/robots.txt
<link rel="shortcut icon" href="{% static 'favicon/favicon.ico' %}"/>

只需要在你的基本文件中添加它,就像第一个答案但ico扩展,并将其添加到静态文件夹

在你的settings.py中添加一个根目录staticfiles:

   STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static')
        ]

创建/静态/图片/ ico。位于

添加图标到你的模板(base.html):

{% load static %}
<link rel="shortcut icon" type="image/png" href="{% static 'images/favicon.ico' %}"/>

并在urls.py中创建一个url重定向,因为浏览器会在/favicon.ico中查找favicon

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

urlpatterns = [
    ...
    path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('images/favicon.ico')))
]

最佳实践:

与你所想的相反,favicon可以是任何大小和任何图像类型。点击这个链接了解详情。

不给你的图标添加链接会降低页面加载速度。

在django项目中,假设你的favicon的路径是:

myapp/static/icons/favicon.png

在你的django模板中(最好是在基本模板中),添加这一行到页面的头部:

<link rel="shortcut icon" href="{%  static 'icons/favicon.png' %}">

注意:

我们假设,静态设置在settings.py中配置得很好。