django
django
django
  • Introduction
  • Django Introduction
  • Basic
    • 환경설정
    • About Django
    • Start Django Project
    • Secret Key 관리하기
    • Settings 분리하기
    • Django App
    • Django View & URL (1)
    • Django Model
      • MySQL 연동
    • Django Admin
    • Django View & URL (2)
    • Django Template
    • Django Template & View & URL
    • Django Static
    • Django form
  • Advanced
    • Django Generic View
    • Django Automated Testing
    • Django Extenstion Template
    • Django Model Package
    • Django OpenSSL setting
  • REST framework
    • Rest API
    • Serializers
    • ViewSet
  • Error
    • 환경설정 zlib 오류발생
    • ModuleNotFoundError
  • 패키지
    • django-debug-toolbar
  • Vue.js 연동하기
Powered by GitBook
On this page
  • 정적 파일 설정
  • settings.py
  • template(.html)
  • collectstatic
  • 참조

Was this helpful?

  1. Basic

Django Static

정적파일(static files)는 웹 페이지를 렌더링하는데 필요한 추가파일( CSS, 이미지, JavaScript )이다.

정적 파일 설정

settings.py

# settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

프로젝트의 기본 설정 값은 다음과 같다. 일반적으로 BASE_DIR 밑에 static이라는 서브 디렉토리를 만들어서 그 안에 파일들을 넣는다. 여기서 static 파일들을 찾는 경로를 나타내는 STATICFILES_DIRS 변수를 추가 설정해야한다.

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

필요에 따라 각각의 Django App마다 정적 파일을 담는 별도의 static 폴더를 둘 수 있다. 이때도 templates와 마찬가지로 app하위에 static 디렉토리 생성후 app명(app/static/app)과 같이 namespace를 명확히 해주는 것이 좋다.

static
├── css
│   └── style.css
├── images
└── js

template(.html)

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

static 파일들을 사용하기 위해서는 템플릿 상단에 `

태그를 먼저 명시해준다. 그 후href="

" 다음과 같이 static tag를 이용하여 해당 리소스를 지정한다. 이때static/` 폴더 이후의 경로만 지정한다.

collectstatic

Django 프로젝트를 deploy할 때, 흩어져있는 정적 파일들을 모아 특정 디렉토리로 옮기는 작업을 할 수 있다.

$ python manage.py collectstatic

collectstatic 명령은 Django 프로젝트와 각 Django App안에 있는 static파일들을 settings.py안에 정의되어 있는 STATIC_ROOT로 옮기는 작업을 수행한다. (이때 STATICFILES_DIRS와 STATIC_ROOT 의 경로는 같으면 안된다.)

참조

PreviousDjango Template & View & URLNextDjango form

Last updated 5 years ago

Was this helpful?

정적파일 reference
Managing static files