Django and css not loading in my project

takrentstockholm
HOBBY

12 days ago

I have reviewed all my files. My project works on my local host on my computer. But CSS files do not load and when opening the URL page, it gives an error that the files are not found. I have reviewed different versions of these events, but nothing worked. Perhaps you can tell me something. Because my project works on my computer in DEBUG=False mode and on the server it does not find styles. I use whitenoise in and my project is entirely on django. I will be very glad if you help me with this. Thank you for your attention)

$10 Bounty

2 Replies

wasayhatzs
FREE

12 days ago

Steps to Fix CSS Loading in Django + WhiteNoise on Railway (DEBUG=False)

1. Install WhiteNoise:

pip install whitenoise

2. Update settings.py:

MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',

'whitenoise.middleware.WhiteNoiseMiddleware',

# other middleware...

]

STATIC_URL = '/static/'

STATIC_ROOT = BASE_DIR / 'staticfiles'

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

3. Collect static files:

After deploying to Railway (or locally), run:

python manage.py collectstatic --noinput

4. Use correct template tags:

In your HTML templates include:

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

5. Set DEBUG=False and redeploy:

Django won’t serve static files itself when DEBUG=False, but WhiteNoise will.

6. Clear browser cache:

Hard-refresh (Ctrl+F5) or open in incognito mode to ensure your latest CSS loads.


takrentstockholm
HOBBY

12 days ago

Thank you for your answer, but I have done all this and checked it manually many times. On my computer the project works and does not show any errors, but when uploaded to the server, the site stops seeing CSS files. Perhaps you need to run some processes through the command line, but I can not find it, since I have only been using this site for 3 days. Help me solve this problem, I will be very grateful.

P.S. Chat GPT and DeepSik do not cope with this. The problem occurs directly when interacting with the server on the site.

Also, where can I provide pieces of code that I have with settings.py

DEBUG = False

ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware', ...
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
WHITENOISE_INDEX_FILE = True
WHITENOISE_ROOT = None
WHITENOISE_MANIFEST_STRICT = False
WHITENOISE_USE_FINDERS = True
WHITENOISE_AUTOREFRESH = True

Here are the important parts of the code that concern the whitenoise.