728x90

✅ 1.템플릿 폴더 구조 설정
Django는 기본적으로 templates/ 폴더에서 테블릿을 찾아 화면에 반환합니다.
프로젝트/
│
├─ myapp/
│ ├─ templates/
│ │ └─ myapp/
│ │ └─ example.html
│ └─ views.py
│
├─ manage.py
└─ settings.py
// settings.py
TEMPLATES = [
{
...
'DIRS': [BASE_DIR / 'templates'], # 프로젝트 전역 템플릿 폴더
...
},
]
✅ 2. HTML 템플릿 기본 문법
- example.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% empty %}
<li>목록이 비어 있습니다</li>
{% endfor %}
</ul>
</body>
</html>
✅ 3. 뷰(View)에서 템플릿 렌더링
- views.py
from django.shortcuts import render
def example_vie(request):
# 예시 뷰 함수
context = {
"title": "Template Example",
'heading': "Django Template Testing",
"description": "This is a simple example of a Django template.",
"items": ["Keyboard", "Mouse", "Monitor", "CPU"],
}
return render (request, "myapp/example.html", context)
✅ 4. URL 연결
- myapp/urls.py (생성)
from django.urls import path
from . import views
urlpatterns = [
path('example/', views.example_view, name= "example"),
]
- config/urls.py
from django.urls import path
from django.contrib import admin
from django.urls import include
# from django.views.generic import RedirectView
# from myapp.views import product_list
urlpatterns = [
path('admin/', admin.site.urls),
path ('', include('myapp.urls'))
# path('', RedirectView.as_view(url='/products/')),
# path('products/', product_list, name='product_list'),
]
✅ 5. 서버 실행
python manage.py runserver
브라우저에서 http://127.0.0.1:8000/example/ 로 접속해 적용되었는지 확인합니다.
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
'Back-End > Django' 카테고리의 다른 글
| [Django] 6장 테스트 작성 (0) | 2025.08.23 |
|---|---|
| [Django] 5장 정적 파일 및 미디어 파일 설정 (1) | 2025.08.11 |
| [Django] 3장. Django 뷰 작성 - 비즈니스 로직 및 데이터 처리 (0) | 2025.04.04 |
| [Django] 2장. Django 모델 정의, 어드민 설정 (0) | 2025.03.25 |
| [Django] 1장. Django란? (0) | 2025.03.07 |