아래 내용은 전부 개발 환경에서의 정적파일 서빙을 설명한다.
웹사이트는 이미지
, JavaScript
, CSS
같은 추가 파일들을 서빙해야 한다. 장고에서는 이러한 추가 파일들을 static files
라고 하며, django.contrib.staticfiles
를 통해 사용할 수 있다.
# settings.py
STATIC_URL = "static/"
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
ex) my_app/static/my_app/example.jpg
장고 앱에 종속된 static파일 외의 static 파일들로 존재할 수 있다.
각 앱의 static 디렉터리 이외에 다른 static파일을 추가하려면 아래와 같이 한다.
STATICFILES_DIRS = [
BASE_DIR / "static",
"/var/www/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일 경우 적용되지 않는다.
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)
django.contrib.staticfiles
는 static 파일들을 한 번에 쉽게 모아주게 한다.
STATIC_ROOT = "/var/www/example.com/static/"
python manage.py collectstatic
이 명령어는 모든 static 폴더들의 static파일들을 STATIC_ROOT 디렉터리에 복사한다.