我只想把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,我可以看到图标。


当前回答

复制你的图标: / yourappname mainapp(例:核心)/静态/ mainapp(例:核心)/ img

然后转到mainapp模板(例如:base.html) 复制这个,在{% load static %}后面,因为你必须先加载静态。

<link href="{% static 'core/img/favi_x.png' %}" rel="shortcut icon" type="image/png" />

其他回答

我在django 2.1.1中尝试了以下设置

base.html

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

settings.py

 STATIC_ROOT = os.path.join(BASE_DIR, 'static')
 STATIC_URL = '/static/'` <br>`.............

项目目录结构

现场观看

在模板文件中

{% load static %}

然后在<head>标签内

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

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


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

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

也可以运行:python manage.py collectstatic

如果你允许的话

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

在你的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')))
]