Django cannot find staticfiles

527 Views Asked by At

When I try to run my localhost server I get the following error:

FileNotFoundError: [Errno 2] No such file or directory: '/static/CSV/ExtractedTweets.csv'

This error is due to the line the line

with open(staticfiles_storage.url('/CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile:

This line of code can be found in a custom python module within my app folder. I have copies of /static/CSV/ExtractedTweets.csv in my project root folder, my app folder and in the folder enclosing my project root and app folders. I also have an additional copy of ExtractedTweets.csv within my app folder.

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

urls.py

from django.conf import settings

urlpatterns = [
    ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

I have placed the file in all possible locations yet django cannot seem to find it. Interestingly, my templates have no problem finding my static CSS files. If anyone has any idea how to resolve this error, please let me know.

2

There are 2 best solutions below

3
On

if you are not looking to deploy this project you can add :

from django.conf import settings    
urlpatterns = [
        path(....),
        path(....),
    ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

or you can try to add :

STATICFILES_DIRS = [
    BASE_DIR / "static",
]

to your setting.py

0
On

I never found a solution to getting the staticfile path however the find() function seems to be an alternative solution.

custommodule.py

from django.contrib.staticfiles.finders import find

with open(find('CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile: