我只想把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工作的简单技巧。

其他回答

一个轻量级的技巧是在你的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工作的简单技巧。

在寻求帮助时偶然发现的。我试图在我的Django项目中实现favicon,它没有显示——想添加到对话中。

当我试图在我的Django项目中实现favicon时,我将“favicon.ico”文件重命名为“my_filename.ico”——图像不会显示。重命名为“favicon.ico”后解决了这个问题并显示了图形。下面是解决我的问题的代码:

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

有时重新启动服务器会有所帮助。

停止服务器,然后重新运行命令:python manage.py runserver 现在应该加载CSS文件了。

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

也可以运行:python manage.py collectstatic

我在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>`.............

项目目录结构

现场观看