자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Django] 5장 정적 파일 및 미디어 파일 설정

728x90

✅ 1. 기본 구조

Django는 static 디렉토리를 통해 CSS, JS, 이미지 같은 정적 파일을 서빙합니다. 

djangobloging/
    myapp/
        static/
            myapp/
                css/
                    style.css
                js/
                    main.js
                images/
                    logo.png
    templates/
        index.html
    settings.py
  • 앱 내부 static/ 폴더 -> 앱전용 파일
  • 공용 지원은 프로젝트 루트에 static/ 폴더 따로 만들어 관리

✅ 2. settings.py 설정

# 정적 파일 URL
STATIC_URL = 'static/'

# 개발 중 정적 파일 위치
STATICFILES_DIRS = [
    BASE_DIR / "static", # 프로젝트 내 static 디렉토리
]

# collectstatic 명령어로 수집된 정적 파일 위치 (배포 시 사용)
STATIC_ROOT = BASE_DIR / "staticfiles"

✅ 3. HTML에 불러오기

템플릿 상단 {% load static %} 선언 후 사용

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" />
<script src="{% static 'js/script.js' %}"></script>
<img src="{% static 'images/logo.png' %}" alt="Logo" />

4. static 폴더 만들기

  • myapp/static/myapp/css/style.css
body {
  background-color: #f0f0f0;
  font-family: Arial, Helvetica, sans-serif;
}

h1 {
  color: darkkhaki;
}
  • myapp/static/myapp/js/main.js
document.addEventListener("DOMContentLoaded", function () {
  console.log("JS Load Success!");
});
  • myapp/static/myapp/images/logo.png  - 이미지는 아무거나

5. 템플릿 작성

  • myapp/templates/index.html
{% load static %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Static Test</title>
    <link rel="stylesheet" href="{% static 'myapp/css/style.css' %}" />
  </head>
  <body>
    <link rel="stylesheet" href="{% static 'myapp/css/style.css' %}" />
    <script src="{% static 'myapp/js/main.js' %}"></script>
    <img src="{% static 'myapp/images/lion.jpg' %}" alt="Logo" />
  </body>
</body>
</html>

✅ 6. setting.py 수정

INSTALLED_APPS = [
    # ...
    'myapp',
    'django.contrib.staticfiles',  # static 사용을 위해 필요
]

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / 'static',  # (공용 static 쓰면)
]

7. 뷰 연결

  • myapp/views.py
from django.shortcuts import render

def index(request):
      return render(request, "index.html");
  • djangobloging/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path ('', views.index, name="index")
 
]

✅ 8. 서버 실행

다음 명령어로 서버를 실행해 테스트해봅니다.

python manage.py runserver

 

브라우에서 http://127.0.0.1:8000/로 접속해 다음과 같은 사항이 뜨면 성공입니다.

  • CSS가 적용된 배경색
  • 이미지 표시
  • 콘솔에 "JS 로드 완료!"메시지

 

 

GitHub - Koras02/djago-bloging: https://thinky.tistory.com/category/Back-End/Django

https://thinky.tistory.com/category/Back-End/Django - Koras02/djago-bloging

github.com

 

728x90
LIST