Search code examples
djangocreate-react-appfavicon

How do I get Django to load my favicon from my React build directory?


I am using Django and React to create a web application. When it comes to my React Development server, my favicon.ico loads like it should, but when I build my files, my Django development server doesn't find and render my favicon, and I have no idea why. I've tried renaming my favicon and changing the file type to .png. When I put my favicon into my static directory, and change the file name from favicon to some thing like "icon.ico", then it loads properly. But, I can't have my favicon in my static directory because CRA won't copy it into that directory when it builds. It's probably something small and simple so I'll show y'all all of the related files. Thanks for any insight!

EDIT: I tried collectstatic , but that did not help

EDIT 2: using {% load static %} but this doesn't work because my favicon is in the same directory as my html file. I should also clarify that import links to the parent directory that holds both my html file and my favicon file don't register for some reason.

The import in my build/index.html: <link rel="shortcut icon" type="image/x-icon" href="./favicon.ico"/>

urls.py


from django.contrib import admin
from django.urls import include, path, re_path
from django.conf.urls import include, url
from backend import views
from django.views.generic.base import RedirectView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('backend.urls')),
    path(r'^api/<int:pk>$', include('backend.urls')),
    path(r'^api/<int:pk>$/', include('backend.urls')),
    url(r'^.*$', views.index),

]

my settings.py static settings:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(FRONTEND, 'build/static/'),

]

CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000',
)

Also, let me know if the problem could be in another file


Solution

  • The problem is that the django url routing has no access to the favicon.ico since CRA puts it in /build and all your static files are served from /build/static.

    Assuming you haven't ejected, a hacky solution is to copy the favicon.ico into the static folder in your build step in package.json scripts section:

    "build": "react-scripts build && cp build/favicon.ico build/static/favicon.ico"
    

    and then in the html template in /public, set the favicon.ico url to

    <link rel="shortcut icon" href="/static/favicon.ico">
    

    instead of %PUBLIC_URL%/favicon.ico.

    If you have ejected the CRA, you can update your webpack config to move the favicon.ico directly into /build/static