본문 바로가기
Programming/Django

Django Template 생성하기

by 느리게 걷는 즐거움 2024. 7. 4.
반응형

Django Template 생성하기

Django는 파이썬 기반의 웹 프레임워크로, 웹 애플리케이션을 빠르고 쉽게 개발할 수 있도록 도와줍니다. 그 중에서도 템플릿 시스템은 매우 강력하여, 백엔드에서 생성한 데이터를 손쉽게 프론트엔드에 전달할 수 있게 해줍니다. 이번 포스팅에서는 Django의 템플릿 파일을 생성하고 `render` 함수를 이용해 템플릿에 파라미터를 전달하는 방법에 대해 알아보겠습니다.

Django 프로젝트 설정하기

우선, Django 프로젝트와 앱을 설정해보겠습니다.

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

`myapp`을 생성한 후에는 `myproject/settings.py` 파일에 `myapp`을 추가해줍니다.

# myproject/settings.py

INSTALLED_APPS = [
    ...
    'myapp',
    ...
]

Django Template 폴더 위치 이해하기

Django에서 템플릿 파일을 찾는 기본 위치는 프로젝트의 설정 파일(`settings.py`)에서 설정됩니다. 이를 위해 `TEMPLATES` 설정을 사용합니다. 기본적으로, Django는 앱 디렉토리 내의 `templates` 폴더를 검색하고 프로젝트 수준에서 추가적으로 템플릿 경로를 설정할 수도 있습니다.

`TEMPLATES` 설정은 `settings.py` 파일에서 찾을 수 있으며, 다음과 같은 형식을 가집니다:

# myproject/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]

여기서 중요한 설정 항목들을 살펴보겠습니다:

   
DIRS 이 리스트는 Django가 템플릿을 찾을 추가 디렉토리를 정의합니다. 

위의 예시에서 `os.path.join(BASE_DIR, 'templates')`는 프로젝트의 루트 디렉토리 아래에 있는 `templates` 디렉토리를 포함하도록 설정합니다. 

`BASE_DIR`은 일반적으로 프로젝트의 루트 디렉토리를 가리키는 변수입니다.
APP_DIRS `True`로 설정되면, Django는 각 앱 디렉토리 내의 `templates` 폴더도 검색합니다. 이 설정은 보통 각 앱의 템플릿 파일을 분리하여 관리할 때 유용합니다.

위의 설정을 통해 Django는 다음 경로들을 검색하게 됩니다:

  • `myproject/templates/` (프로젝트의 루트 디렉토리 아래에 있는 `templates` 폴더)
  • 각 앱 디렉토리 내의 `templates` 폴더 (예: `myapp/templates/`)
예시: 프로젝트와 앱 디렉토리 구조
myproject/
    myproject/
        settings.py
        urls.py
        wsgi.py
    myapp/
        templates/
            myapp/
                my_template.html
        views.py
    templates/
        base.html

위 구조에서

  • 프로젝트 수준 템플릿은 `myproject/templates/`에 위치합니다.
  • 앱 수준 템플릿은 `myproject/myapp/templates/myapp/`에 위치합니다.

이제 Django는 템플릿을 렌더링할 때, 위의 경로들에서 템플릿 파일을 검색합니다. 이와 같이 `settings.py` 파일에서 `TEMPLATES` 설정을 통해 템플릿 파일의 기본 위치를 정의하고, 프로젝트와 앱 구조에 맞게 템플릿 파일을 배치하여 효율적으로 관리할 수 있습니다.

뷰(View) 작성하기

이제 `myapp` 폴더 내에 있는 `views.py` 파일에 뷰를 작성해보겠습니다. `render` 함수를 사용하여 템플릿과 데이터를 렌더링할 것입니다.

# myapp/views.py

from django.shortcuts import render

def my_view(request):
    # 템플릿에 전달할 데이터 정의
    context = {
        'name': 'Django',
        'message': 'Welcome to Django!'
    }
    return render(request, 'myapp/my_template.html', context)

여기서 `render` 함수는 세 가지 인자를 받습니다:

정보 내용
request 현재 요청에 대한 정보.
myapp/my_template.html 렌더링할 템플릿 파일의 경로.
context (딕셔너리) 템플릿에 전달할 데이터.

템플릿 작성하기

이제 `myapp/templates/myapp/` 폴더를 만들고 그 안에 `my_template.html` 파일을 생성합니다.

<!-- myapp/templates/myapp/my_template.html -->

<!DOCTYPE html>
<html>
<head>
    <title>Django Template</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <p>{{ message }}</p>
</body>
</html>

템플릿에서는 `{{ }}` 구문을 사용하여 `context` 딕셔너리에서 전달된 데이터를 출력합니다.

URL 설정하기

`urls.py` 파일을 수정하여 `my_view`를 URL에 매핑합니다. 먼저 `myapp` 폴더에 `urls.py` 파일을 생성합니다.

# myapp/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.my_view, name='my_view'),
]

그리고 `myproject/urls.py` 파일을 수정하여 `myapp`의 `urls.py`를 포함시킵니다.

# myproject/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

서버 실행 및 확인

모든 설정이 완료되었으니, 이제 서버를 실행해보겠습니다.

python manage.py runserver


웹 브라우저에서 `http://127.0.0.1:8000/`로 접속하면 다음과 같은 페이지를 확인할 수 있습니다.

Hello, Django!
Welcome to Django!

 

 

반응형

'Programming > Django' 카테고리의 다른 글

Django에서 Python Logger 사용하기  (0) 2024.07.05
Django에서 Template 폴더 설정하기  (0) 2024.07.04