Django의 HTML 파일들은 templates 폴더 밑에 위치한다. 일반적으로 CSS, JS 파일은 HTML 파일이 있는 폴더의 하위 폴더를 만들고, 그 하위 폴더에 넣어도 경로로 인식된다. 하지만 장고는 css, js 파일들을 static 파일이라고 부르고, 별도의 폴더에서 관리하도록 하고 있다.
ㅤ
단순히 디렉토리만 만든다고 해서 인식되는 것 아니고, settings.py도 함께 수정해야 한다.
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”. - from Django official website -
# settings.py
STATIC_URL = '/static/' # {% load static %} 이랑 일치(?)
STATICFILES_DIRS = [ # css, js 파일을 넣을 디렉토리
BASE_DIR / 'static',
]
ㅤ
여러 블로그에서 위와 같이 소개하고 있어, 일단 똑같이 작성하고 실행해 보았다. 하지만 실행하면 문자열(BASE_DIR)과 문자열('static') 사이에 슬래쉬('/')가 있다며, TypeError가 발생한다.
File "C:\root\my_project\project\settings.py", line 174, in <module>
BASE_DIR / 'static',
~~~~~~~~~^~~~~~~~~~
TypeError: unsupported operand type(s) for /: 'str' and 'str'
[파이썬 코드]
import os
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
[HTML 코드]
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="{% static 'css/my.min.css' %}"/>
<link rel="stylesheet" href="{% static 'plugins/css/all.min.css' %}" />
최종적으로 웹브라우저에서는 ROOT 하위에 static 디렉토리에 css, js 등 파일이 들어가는 것처럼 보이게 된다. (http://127.0.0.1:8000/static/css/my.min.css)
<link rel="stylesheet" href="/static/css/my.min.css"> <link rel="stylesheet" href="/static/plugins/css/all.min.css">
| 참고 |
1. https://docs.djangoproject.com/en/4.2/howto/static-files/#:~:text=Websites%20generally%20need%20to%20serve,can%20serve%20these%20static%20files.
2. https://0ver-grow.tistory.com/912