본문 바로가기

Python/Django

[Django] Class based View - TemplateView

이번에는 클래스 기반의 뷰에 대해서 알아보겠습니다.

클래스 기반 뷰를 사용하여 템플릿을 뷰에 URL로 연결하는 아이디어부터 시작하여,
클래스 기반 뷰의 이면에 있는 개념에 대한 기본적인 내용을 살펴보도록 하겠습니다.

 

 

(django) ~> django-admin startproject school
(django) ~> cd school
(django) ~\review_01> python manage.py startapp classroom

 

 

./school/classrom/templates/classroom/home.html 생성

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home.html</title>
</head>
<body>
    <h1>Welcome to home.html</h1>
</body>
</html>

 

 

./school/classrom/views.py 수정 - home_view(request) 정의

 

from django.shortcuts import render

# Create your views here.
def home_view(request):
    return render(request, 'classroom/home.html')

 

 

./school/classrom/urls.py 생성 - path 추가.

 

from django.urls import path
from . import views

app_name = 'classroom'

# domain.com/classroom
urlpatterns = [
    path('', views.home_view, name='home'), # path expects a function!
]

 

 

./school/school/urls.py 수정 - path 추가

 

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

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

 

 

settings.py - ClassroomConfig 추가

 
INSTALLED_APPS = [
    'classroom.apps.ClassroomConfig', <==== 추가
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

 

 

school/models.py 수정 - 

 

from django.db import models

# Create your models here.
class Teacher(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    subject = models.CharField(max_length=30)

    def __str__(self):
        return f'{self.first_name} {self.last_name} teaches {self.subject}.'

 

 

makemigrations - python manage.py makemigrations

 

migrate - python manage.py migrate

 

runserver - python manage.py runserver

 

 

서버 실행

 

 

여기까지는 우리가 이전에 배웠던 기본적인 템플릿(함수기반 템플)입니다.

 


 

이제부터 TemplateView 에 대해서 알아보겠습니다.

 

 

school/classroom/views.py - TemplateView 임포트

 

from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.
# def home_view(request):
#     return render(request, 'classroom/home.html')

class HomeView(TemplateView):
    template_name = 'classroom/home.html'

class ThankYouView(TemplateView):
    template_name = 'classroom/thank_you.html'

 

 

school/classroom/urls.py - .as_view() 함수 사용이 핵심

 

from django.urls import path
from . import views

app_name = 'classroom'

# domain.com/classroom
urlpatterns = [
    # path('', views.home_view, name='home'), # path expects a function!
    path('', views.HomeView.as_view(), name='home'), # 클래스를 가지고 경로에 대한 함수를 반환
    path('thank_you/', views.ThankYouView.as_view(), name='thank_you'), 
]

 

 

school/classroom/templates/classroom/home.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home.html</title>
</head>
<body>
    <h1>Welcome to home.html</h1>
    <ul>
        <li>
            <a href="{% url 'classroom:thank_you' %}">THANK YOU PAGE LINK</a>
        </li>
    </ul>
</body>
</html>

 

 

school/classroom/templates/classroom/thank_you.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thank you</title>
</head>
<body>
    <h1>Thank you ~~~</h1>
</body>
</html>

 

 

결과 화면