Django

Django 실습(2) Templates 분리와 상속으로 블로그 만들기

UserDonghu 2023. 10. 10. 19:28

templates안에 html파일들을 더 효율적으로 관리하기 위해서 각각 app안에 templates폴더를 만드는것이 아닌, BASE_DIR 에 templates폴더를 따로 만들어서 관리할 수 있다.

 

만약 mysite라는 프로젝트에 main이라는 앱과 blog라는 앱이 있다면, mysite / main / templates 와 mysite / blog / templates 가 아닌, mysite / templates / main , mysite / templates / blog 폴더를 만들어서 한곳에 관리를 한다.

 

BASE_DIR : 프로젝트 최상위 폴더 ex) mysite

 

템플릿 태그

{{ 변수명 }}

{% 템플릿 문법 %}

 

템플릿 상속 : 홈페이지를 조각내어 각각의 html로 관리하는 기법

부모 html

<!-- 위 코드 -->

{% block 이름 %}
<!-- 코드 들어갈 부분 -->
{% endblock %}

<!-- 아래 코드 -->

 

자식 html

{% extends '부모 html 파일' %}

{% block 이름 %}
<!-- 넣을 코드 -->
{% endblock %}

실습

mysite 폴더 생성 후, 가상환경 세팅, 장고 설치,  tutorialdjango 프로젝트 시작, mange.py migrate, main과 blog 앱 생성, settings.py에 app추가

 

mysite / main / urls.py

from django.urls import path
from . import views

app_name = 'main'

urlpatterns = [
    path('', views.index, name='index'),
    path('contact/', views.contact, name='contact'),
    path('about/', views.about, name='about'),
]

 

mysite / blog / urls.py

from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:pk>/', views.post, name='post'),
]

 

mysite / templates 폴더 추가

mysite / templates 안에 main 과 blog 폴더 추가, html 파일들 추가

 

setting.py 에서 templates 기본 폴더 변경

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / 'templates'], # 이 부분 추가해주기
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

 

main 의 views.py 수정

from django.shortcuts import render

def index(request):
    return render(request, 'main/index.html')

def about(request):
    return render(request, 'main/about.html')

def contact(request):
    return render(request, 'main/contact.html')

 

blog 의 views.py 수정

from django.shortcuts import render
from django.http import HttpResponse

db = [
    {
        'id': 1,
        'title': '나의 죽음을 알리지 마라',
        'contents': '첫번째 게시물 내용',
        'created_at': '2023-10-10 00:00:00',
        'updated_at': '2023-10-11 00:00:00',
        'author': '이순신',
        'category': '일상',
        'tags': '체력단련, 무예단련',
        'thumbnail': 'https://picsum.photos/200/300',
    },
    {
        'id': 2,
        'title': '왕이 되고 싶은 나',
        'contents': '두번째 게시물 내용',
        'created_at': '2023-10-12 00:00:00',
        'updated_at': '2023-10-13 00:00:00',
        'author': '김유신',
        'category': '테크',
        'tags': '맥북, 아이폰, 파이썬',
        'thumbnail': 'https://picsum.photos/200/300',
    },
    {
        'id': 3,
        'title': '한글은 최고야',
        'contents': '세번째 게시물 내용',
        'created_at': '2023-10-14 00:00:00',
        'updated_at': '2023-10-15 00:00:00',
        'author': '세종대왕',
        'category': '취미',
        'tags': '그림, 서예',
        'thumbnail': 'https://picsum.photos/200/300',
    },
]

def index(request):
    return render(request, 'blog/index.html', {'db': db})

def post(request, pk):
    if len(db) >= pk:
        return render(request, 'blog/post.html', {'db': db[pk-1]})
    else:
        return HttpResponse('잘못된 접근입니다.')

 

 

templates 에 부모 html 만들기

mysite / templates / menu.html

<!DOCTYPE html>
<html lang="ko-KR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Menu</title>
</head>

<body>
    <h1>위인의 블로그</h1>
    <a href="{% url 'main:index' %}">main</a>
    <a href="{% url 'main:about' %}">about</a>
    <a href="{% url 'main:contact' %}">contact</a>
    <a href="{% url 'blog:index' %}">index</a>
	
    {% block content %}
    <!-- 자식 html 코드 들어갈 부분 -->
    {% endblock %}
    
</body>

</html>

 

자식 html 상속 받기

templates / main / index.html, contact.html, about.html

{% extends 'menu.html' %}

{% block content %}
<p>이곳은 메인화면 or about or contact 입니다.</p>
{% endblock %}

 

templates / blog / index.html

{% extends 'menu.html' %}

{% block content %}

{% for i in db %}
<div>
    <h3><a href="./{{i.id}}">{{i.title}}</a></h3>
    <p>{{i.contents}}</p>
    <p>{{i.author}}</p>
</div>
{% endfor %}

{% endblock %}

 

templates / blog / post.html

{% extends 'menu.html' %}

{% block content %}

<div>
    <h2>{{db.title}}</h2>
    <p>category : {{db.category}}</p>
    <p>author : {{db.author}}</p>
    <img src="{{db.thumbnail}}">
    <p>{{db.contents}}</p>
    <p>created : {{db.created_at}}</p>
    <p>updated : {{db.updated_at}}</p>
    <p>tag : {{db.tags}}</p>
</div>

{% endblock %}

 

결과

main
about
contact
blog
blog/1
blog/3