troubleshooting2025-01-10·7 min·230/348

Django Static 파일 서빙 에러 해결 방법

Django에서 static 파일이 제대로 로드되지 않는 문제를 진단하고 해결하는 방법을 알아봅니다.

Django Static 파일 서빙 에러 해결 방법

Django 프로젝트에서 static 파일(CSS, JavaScript, 이미지 등)이 브라우저에 제대로 표시되지 않는 문제는 흔히 발생합니다. 특히 개발 서버와 프로덕션 환경에서의 차이로 인해 혼란이 생길 수 있습니다.

Environment

$ python --version
Python 3.11.5

$ pip show django
Name: Django
Version: 4.2.5

$ pip show whitenoise
Name: whitenoise
Version: 6.5.0

Problem: Static 파일 404 에러

$ curl -I http://localhost:8000/static/css/style.css
HTTP/1.1 404 Not Found
Content-Type: text/html

$ python manage.py collectstatic --noinput
1325 static files copied to '/home/user/project/staticfiles'.

collectstatic은 성공적으로 실행되었지만, 파일이 서빙되지 않습니다.

Analysis: Django Static Files 설정 분석

# settings.py 확인
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# These are the key settings
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

문제를 진단하기 위해 Django shell에서 확인합니다:

$ python manage.py shell
>>> from django.conf import settings
>>> print(f"STATIC_URL: {settings.STATIC_URL}")
>>> print(f"STATIC_ROOT: {settings.STATIC_ROOT}")
>>> print(f"STATICFILES_DIRS: {settings.STATICFILES_DIRS}")

>>> from django.contrib.staticfiles.finders import find
>>> print(f"Found CSS: {find('css/style.css')}")

출력:

STATIC_URL: /static/
STATIC_ROOT: /home/user/project/staticfiles
STATICFILES_DIRS: ['/home/user/project/static']
Found CSS: None

파일이 찾이지 않습니다. STATICFILES_DIRS에 올바른 경로가 설정되어 있지 않을 수 있습니다.

Solution: Static 파일 서빙 문제 해결

방법 1: 개발 환경에서의 설정

# settings.py
DEBUG = True

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

# Verify directories exist
import os
for directory in STATICFILES_DIRS:
    if not os.path.exists(directory):
        os.makedirs(directory)
        print(f"Created directory: {directory}")

방법 2: WhiteNoise 미들웨어 설정

# settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',  # Add this
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

# WhiteNoise settings
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Optional: Enable gzip compression
WHITENOISE_USE_FINDERS = True
WHITENOISE_AUTOREFRESH = True

방법 3: Nginx 설정 (프로덕션)

# nginx.conf
server {
    listen 80;
    server_name example.com;

    # Static files
    location /static/ {
        alias /home/user/project/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Media files
    location /media/ {
        alias /home/user/project/media/;
    }

    # Django application
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

Advanced: Static 파일 최적화

ManifestStaticFilesStorage 활용

# settings.py
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

# This creates hashed filenames:
# css/style.css -> css/style.a1b2c3d4e5f6.css

Custom Static Files Finder

# myapp/finders.py
from django.contrib.staticfiles.finders import BaseFinder
import os

class CustomStaticFinder(BaseFinder):
    def find(self, path, all=False):
        custom_path = os.path.join('/custom/static/path', path)
        if os.path.exists(custom_path):
            if all:
                return [custom_path]
            return custom_path
        return None
    
    def list(self, ignore_patterns):
        custom_path = '/custom/static/path'
        if os.path.exists(custom_path):
            for root, dirs, files in os.walk(custom_path):
                for filename in files:
                    yield filename, os.path.join(root, filename)

Template에서 Static 파일 참조

{% load static %}



    


    

Troubleshooting Checklist

# 1. collectstatic 실행
$ python manage.py collectstatic --noinput -v 2

# 2. STATICFILES_DIRS 경로 확인
$ python manage.py shell -c "from django.conf import settings; print(settings.STATICFILES_DIRS)"

# 3. 파일 존재 여부 확인
$ find ./static -name "*.css" | head -5
$ ls -la staticfiles/

# 4. Django 개발 서버 로그 확인
$ python manage.py runserver 0.0.0.0:8000 --verbosity 3

# 5. WhiteNoise 테스트
$ python manage.py findstatic css/style.css

Lessons Learned

  1. DEBUG 설정 이해: DEBUG=True일 때 Django 개발 서버는 자동으로 static 파일을 서빙합니다.

  2. collectstatic 필수: 프로덕션 환경에서는 반드시 collectstatic을 실행하여 모든 static 파일을 STATIC_ROOT로 수집하세요.

  3. WhiteNoise 간편함: 서버 설정 없이 Django 앱에서 static 파일을 서빙하려면 WhiteNoise 미들웨어가 가장 간단한 방법입니다.

  4. 캐싱 전략: 프로덕션에서는 static 파일에 대한 캐싱 헤더를 설정하여 브라우저 캐시를 활용하세요.

  5. 파일 경로 주의: STATICFILES_DIRS에 설정한 경로는 Django 프로젝트 루트를 기준으로 합니다.


This blog does not accept any external sponsorships, affiliate marketing, or ad revenue.