[Django]-404 Static file not found – Django

3👍

you need to add the static & media files config in the urls.py , like this

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] 
urlpatterns  +=  static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

the django docs : https://docs.djangoproject.com/en/3.1/howto/static-files/

0👍

For those who still looking for static file solution, please try Django package Whitenoise. It is easy to install and easy to use if you followed the instructions.

some simplified steps:

  1. Collect static – make sure static files existing before install

     python manage.py collectstatic
    
  2. Install the Whitenoise – this step depends how you managed the packages, update proper file(e.g. Pipfile or requirements.txt) and install. Below command just a example to install the package.

     pip install whitenoise
    
  3. Update the static root in settings.py

     STATIC_ROOT = BASE_DIR / "staticfiles"
    
  4. Add the following to your MIDDLEWARE in settings.py – from Whwitenoise docs, Whitenoise package should place after django.middleware.security.SecurityMiddleware

     `MIDDLEWARE = [
       'django.middleware.security.SecurityMiddleware',
       'whitenoise.middleware.WhiteNoiseMiddleware', #add it here exactly after security middleware
       ...
     ]
    
  5. now restart or rebuild the app to check whether it is working for you.

Please check Whitenoise docs if you running into issue about installing the Whitenoise(Whitenoise docs)

a message for using staticfiles_urlpatterns:
this only works when DEBUG=True in settings.py which means you should NOT use it for production environment. see reference here

Leave a comment