본문 바로가기
카테고리 없음

[Django] 3. Django Templates & Static Files 정리

by Mandy's 2025. 7. 20.

1. ✅ 템플릿(Templates)이란?

  • HTML을 동적으로 생성하기 위한 Django의 도구
  • Django Template Language(DTL) 사용:
    • {{ }}: 변수 출력
    • {% %}: 조건문, 반복문, 태그 처리

2. ✅ 템플릿 설정 방법

🔹 DIRS vs APP_DIRS

항목설명
DIRS 전역 템플릿 디렉토리 지정 (ex: templates/)
APP_DIRS=True 각 앱의 내부 templates/ 폴더 자동 탐색
 

일반적으로 앱 안에 templates/app_name/파일.html 구조로 저장하면 설정이 간단해짐


3. ✅ 템플릿 렌더링 예시

from django.shortcuts import render

def monthly_challenge(request, month):
    try:
        challenge_text = monthly_challenges[month]
        return render(request, "challenges/challenge.html", {
            "month_name": month,
            "text": challenge_text
        })
    except:
        return HttpResponseNotFound("404 Error")

4. ✅ Template Language - 주요 문법

  • Variable Interpolation (변수 치환)
    → {{ month_name }}, {{ text }}
  • Filters
    → {{ month_name|title }} → capitalize() 역할
  • for 반복문
{% for month in months %}
  <li><a href="{% url "month-challenge" month %}">{{ month|title }}</a></li>
{% endfor %}
  • if 조건문
{% if text %}
  <h2>{{ text }}</h2>
{% else %}
  <p>There is no challenge for this month yet!</p>
{% endif %}

5. ✅ Template Inheritance (템플릿 상속)

  • 중복 제거를 위한 구조화
templates/
├── base.html
└── challenges/
    ├── index.html
    └── challenge.html
  • base.html: 공통 레이아웃 (header, footer 등)
  • extends, block, include로 재사용
{% extends "base.html" %}

{% block content %}
  <h1>{{ month_name }}</h1>
  <p>{{ text }}</p>
{% endblock %}

6. ✅ Static Files 정리 (CSS, JS, 이미지)

  • 정적 파일 경로 설정:
    • 앱 내부: static/challenges/challenges.css
    • 전역 설정: STATICFILES_DIRS에 추가
  • 템플릿에서 로딩:
{% load static %}
<link rel="stylesheet" href="{% static 'challenges/challenges.css' %}">
 
  • 정적 파일 위치 예시:
my_project/
├── static/
│   └── css/
│       └── styles.css
├── challenges/
│   └── static/
│       └── challenges/
│           └── challenge.css

7. ✅ 404 템플릿 만들기

  • 404.html 파일 생성하여 사용자 친화적인 에러 페이지 제공
{% extends "base.html" %}

{% block page_title %}404 Error{% endblock %}

{% block content %}
  <h1>We could not find that page!</h1>
{% endblock %}
  • View에서 사용:
from django.template.loader import render_to_string

except:
    response_data = render_to_string("404.html")
    return HttpResponseNotFound(response_data)

8. ✅ DEBUG = True 일 때 특징

  • 에러 발생 시 상세 페이지 출력
  • 정적 파일을 Django가 직접 서빙
  • 템플릿 변경 시 자동 반영 (서버 재시작 불필요)

📌 전체 흐름 요약

기능설명
Template HTML + DTL로 동적 페이지 생성
Variable {{ var }} 로 출력
Filter `
Static Files 정적 파일(CSS/JS) 관리
Template Inheritance base.html 확장해 중복 제거
404 템플릿 사용자 친화적 에러 페이지 제공
DEBUG 개발 중 유용한 도구 활성화 상태