Wednesday, 12 May 2021

Unable to locate react static files when serving from django staticfiles and uploading to heroku

I'm trying to add a Django backend and a react frontend to Heroku. Following this tutorial. I'm using whitenoise for serving static files.

When runnning python manage.py collectstatic I keep getting the same error:

django.core.exceptions.SuspiciousFileOperation: The joined path (C:\Users\<name>\Documents\combined_connect\static\media\background-pattern.f6347303.png) is located outside of the base path component (C:\Users\<name>\Documents\combined_connect\staticfiles)

This command is also run by heroku python hooks when deploying. The python hook runs after the react hook, so the react build folder is definitely there. For testing purposes I also ran build locally for when I call the collectstatic command.

The problem is something to do with how I'm defining static roots, but for the life of me I can't figure it out. I've used multiple tutorials, the django docs on static files, and the heroku dev docs on static files.

Why is it looking for my media files (background-pattern.png etc.) in static? On collectstatic everything gets put into the staticfiles directory. No matter what I change the file names or variables to, that error about the lookup conflict between staticfiles and static always happens.

Here's how I'm defining them:

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
​

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'build')], # pointing to the React build folder
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = 'build/static/'
​
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'build/static'),
)

Here's how the project is structured:

enter image description here

EDIT: Using this config, I can serve the backend just fine. If I go to the root url /, I see the Django 404 page instead o my React homepage. Going to /admin works perfectly, and I can call /api/ endpoints.



from Unable to locate react static files when serving from django staticfiles and uploading to heroku

No comments:

Post a Comment