Django์์ ๋ทฐ์ ํ์ํ ๋ด์ฉ๋ค์ ์ฌ์ฌ์ฉํ ์ ์๊ฒ ํด์ฃผ๋ ๊ธฐ๋ณธ ํด๋์ค
๋ค๋ฅธ ํ์ฅ ๋ทฐ ํด๋์ค๋ค(TemplateView, CreateView ๋ฑ)์ ์ต์์ ๋ถ๋ชจ ํด๋์ค
View ํด๋์ค์์ ํ์ฅํด์ Template ๋ ๋๋ง์ ์ต์ํ์ ์ฝ๋๋ก ์์ฑํ ์ ์๊ฒ ํด์ฃผ๋ Django ํด๋์ค
template_name
๋ฉค๋ฒ ํ๋์ ํ
ํ๋ฆฟ์ ์ง์
class View:
def get(self, request: HttpRequest):
return response: HttpResponse
def post(self, request: HttpRequest):
return response: HttpResponse
class TemplateView:
template_name: str
def get_context_data(self):
return context: dict
"""taskproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
urls.py
๋ฅผ ๋ณด๋ฉด FBV, CBV์ ๊ฒฝ์ฐ ๋ฐ ์ต์์ URLConf ์ค์ ๋ฑ์ ๋ํ ์์๊ฐ ์์ฃผ ์ ๋์์์ผ๋ ์ด๋ฅผ ์ฐธ๊ณ ํด๋ ๋๋ค.from django.views.generic.base import TemplateView
from articles.models import Article
class HomePageView(TemplateView):
template_name = "home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["latest_articles"] = Article.objects.all()[:5]
return context
TemplateView๋ URL์ ์บก์ฒ๋ ๋งค๊ฐ๋ณ์๊ฐ ํฌํจ๋ ์ปจํ ์คํธ๋ฅผ ์ฌ์ฉํ์ฌ ์ง์ ๋ ํ ํ๋ฆฟ์ ๋ ๋๋งํ๋ค.
TemplateView๋ ๊ธฐ๋ณธ์ ์ผ๋ก GET๋ฉ์๋๋ฅผ ์ํ ๋ทฐ๋ก POST๋ฉ์๋๋ ๋ฐ๋ก ์์ฑํ์ง ์์๋ ๋๋ค.
get_context_data
๋ฅผ ์ด์ฉํ์ฌ ํ
ํ๋ฆฟ์ ๋๊ฒจ์ค ๋ณ์๋ฅผ ๋ฆฌํดํด์ฃผ๋ฉด ๋๋ค.
์ด ๋ทฐ๋ ์๋์ ๋ฉ์๋์ ์์ฑ์ ์์๋ฐ๋๋ค.
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render, HttpResponseRedirect, redirect
from django.views.generic import TemplateView, CreateView, UpdateView, DeleteView, ListView, DetailView, FormView
from .models import Task, ChecklistItem
from django.utils import timezone
from django.core.paginator import Paginator
from django.urls import reverse_lazy
class TaskListView(TemplateView):
template_name = 'pages/task_list.html'
def get_context_data(self, **kwargs):
tasks = Task.objects.all()
return {
'tasks' : tasks,
}