Django에서는 하나의 URL 요청을 처리하는 방식으로
함수형 뷰(FBV) 와 클래스형 뷰(CBV) 를 제공한다.
클래스형 뷰는 HTTP 메서드별 동작을 구조적으로 분리할 수 있어
폼 처리나 CRUD 로직에서 특히 유용하다.
이번 글에서는 클래스형 뷰의 기본 구조와 동작 흐름을 간단히 정리한다.
1. 클래스형 뷰란 무엇인가
클래스형 뷰는
하나의 View를 클래스로 정의하고,
HTTP 메서드(GET, POST 등)를 메서드로 분리해 처리하는 방식이다.class PostCreateView(View): def get(self, request): ... def post(self, request): ...
요청 메서드에 따라 Django가 자동으로 대응되는 메서드를 호출한다.
2. GET과 POST의 역할 분리
def get(self, request):
# Method: Get
post_form = PostForm()
return render(request, 'posts/post_form.html', {'form': post_form})
def post(self, request):
# Method: Post
post_form = PostForm(request.POST)
if post_form.is_valid():
new_post = post_form.save()
return redirect('post-detail', post_id=new_post.id)
조회와 처리 로직이 명확히 분리된다.
3. URL과 클래스형 뷰 연결 방식
path('new/', views.PostCreateView.as_view(), name='post-create'),
as_view()는 클래스를 실제 뷰 함수로 변환
4. 클래스형 뷰의 장점 요약
- HTTP 메서드별 책임 분리
- 코드 가독성 향상
- 확장과 재사용에 유리
- CRUD 구조에 잘 맞음
폼 처리, 생성/수정 로직에서 특히 효과적
5. 전체 코드
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from .models import Post
from .forms import PostForm
class PostCreateView(View):
def get(self, request):
post_form = PostForm()
return render(request, 'posts/post_form.html', {'form': post_form})
def post(self, request):
post_form = PostForm(request.POST)
if post_form.is_valid():
new_post = post_form.save()
return redirect('post-detail', post_id=new_post.id) # urlname을 통한 redirect.
return render(request, 'posts/post_form.html', {'form': post_form})
from django.urls import path
from . import views
urlpatterns = [
path('new/', views.PostCreateView.as_view(), name='post-create'),
]
6. 정리하면
클래스형 뷰는
HTTP 메서드(GET, POST)를 기준으로
요청 처리 로직을 구조적으로 분리한 Django 뷰 방식이다.
'Django 프론트& 백엔드 개발' 카테고리의 다른 글
| Django 게시글 생성 View: View 상속 방식과 Generic CreateView 비교 (0) | 2026.01.17 |
|---|---|
| Django 제네릭 뷰(Generic View): 반복되는 View 로직을 줄이는 방법 (0) | 2026.01.17 |
| Django 페이지네이션 구조 이해하기: View와 HTML 템플릿의 역할 분리 (0) | 2026.01.17 |
| href='?page=2'가 현재 경로를 유지하는 이유 (0) | 2026.01.17 |
| GET 메서드에서 경로 스트링과 쿼리 스트링을 사용하는 이유 (0) | 2026.01.17 |