How can I get a favicon to show up in my django app?

后端 未结 13 1527
盖世英雄少女心
盖世英雄少女心 2020-12-02 06:50

I just want to drop the favicon.ico in my staticfiles directory and then have it show up in my app.

How can I accomplish this?

I ha

相关标签:
13条回答
  • 2020-12-02 07:27

    In your settings.py add a root staticfiles directory:

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

    Create /static/images/favicon.ico

    Add the favicon to your template(base.html):

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

    And create a url redirect in urls.py because browsers look for a favicon in /favicon.ico

    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')))
    ]
    
    0 讨论(0)
  • 2020-12-02 07:28

    Came across this while looking for help. I was trying to implement the favicon in my Django project and it was not showing -- wanted to add to the conversation.

    While trying to implement the favicon in my Django project I renamed the 'favicon.ico' file to 'my_filename.ico' –– the image would not show. After renaming to 'favicon.ico' resolved the issue and graphic displayed. below is the code that resolved my issue:

    <link rel="shortcut icon" type="image/png" href="{% static 'img/favicon.ico' %}" />
    
    0 讨论(0)
  • 2020-12-02 07:29

    One lightweight trick is to make a redirect in your urls.py file, e.g. add a view like so:

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

    This works well as an easy trick for getting favicons working when you don't really have other static content to host.

    0 讨论(0)
  • 2020-12-02 07:33

    If you have a base or header template that's included everywhere why not include the favicon there with basic HTML?

    <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
    
    0 讨论(0)
  • 2020-12-02 07:33

    In template file

    {% load static %}
    

    Then within <head> tag

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

    This assumes that you have static files configured appropiately in settings.py.


    Note: older versions of Django use load staticfiles, not load static.

    0 讨论(0)
  • 2020-12-02 07:37
    <link rel="shortcut icon" href="{% static 'favicon/favicon.ico' %}"/>
    

    Just add that in ur base file like first answer but ico extension and add it to the static folder

    0 讨论(0)
提交回复
热议问题