Django 정적파일 공식문서 - 개발환경

hyuckhoon.ko·2023년 10월 17일
0

정적 파일을 어떻게 처리할까

아래 내용은 전부 개발 환경에서의 정적파일 서빙을 설명한다.

웹사이트는 이미지, JavaScript, CSS 같은 추가 파일들을 서빙해야 한다. 장고에서는 이러한 추가 파일들을 static files 라고 하며, django.contrib.staticfiles를 통해 사용할 수 있다.

static 파일 설정

1. INSTALLED_APPS에 django.contrib.staticfiles 추가

2. STATIC_URL 정의

# settings.py
STATIC_URL = "static/"

3. static 템플릿 태그 적용

{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">

4. static 디렉터리에 static 파일들 저장

ex) my_app/static/my_app/example.jpg

장고 앱에 종속된 static파일 외의 static 파일들로 존재할 수 있다.
각 앱의 static 디렉터리 이외에 다른 static파일을 추가하려면 아래와 같이 한다.

STATICFILES_DIRS = [
    BASE_DIR / "static",
    "/var/www/static/",
]

5. 개발환경에서 static 파일 서빙

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

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

그러나, 오직 DEBUG=True일 때만 가능하며, settings에 정의된 STATIC_URL이 static/과 같을 때에만 적용된다. 즉, http://static/example.com 과 같은 URL일 경우 적용되지 않는다.

6. 개발환경에서 유저가 업로드한 미디어 파일 서빙

django.views.static.serve()로 정의된 MEDIA_ROOT로부터 유저가 업로드한 미디어 파일을 서빙할 수 있다.(프로덕션 환경에서 적합한 방식은 아니다.)

예를 들어,
settings.py에 MEDIA_URL이 media/로 정의 돼 있다면,

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

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

7. 배포

django.contrib.staticfiles 는 static 파일들을 한 번에 쉽게 모아주게 한다.

  1. STATIC_ROOT 정의
STATIC_ROOT = "/var/www/example.com/static/"
  1. collecstatic 명령어 실행
python manage.py collectstatic

이 명령어는 모든 static 폴더들의 static파일들을 STATIC_ROOT 디렉터리에 복사한다.

  1. 해당 static 파일들을 서빙할 웹서버를 사용한다.

0개의 댓글