클래스형 뷰

Ethan·2024년 1월 19일
0

Dear

목록 보기
7/13

지금까지는 함수형 뷰를 사용했다. 함수형 뷰는 모든 로직을 직접 구현하기 때문에 직관적이지만, 클래스형 뷰를 사용하면 이미 작성된 상위 클래스를 상속받을 수 있어 더 간편하고 빠르게 뷰를 작성할 수 있다.

우리는 이미 클래스를 사용했다. <dear> 프로젝트의 Post 모델을 살펴보면 다음과 같다.

#posts/models.py > Post

class Post(models.Model):
    title = models.CharField(max_length=50, unique=True, error_messages={"unique":"이미 같은 제목의 게시글이 존재합니다"})
    content = models.TextField(validators=[MinLengthValidator(10, "10자 이상 입력해주세요"),
                                           validate_symbols])
    dt_created = models.DateTimeField(verbose_name="Date Created", auto_now_add=True)
    dt_modified = models.DateTimeField(verbose_name="Date Modified", auto_now=True)
    
    def __str__(self):
        return self.title

Post 모델은 장고의 modles.Model 클래스를 상속받아 사용하기 때문에 관련된 기능을 직접 구현하지 않아도 된다. 또한 __str__ 함수를 클래스 안에서 구현한다.

장고는 많은 개발자들이 자주 사용하는 여러 기능들을 클래스로 제공한다. CRUD와 같은 복잡한 기능들을 상위 클래스상속받으면 뷰를 더 쉽고 간편하게 작성할 수 있다.


1. 함수형 뷰를 클래스형 뷰로 변경

기존에 작성한 post_create 뷰를 클래스형 뷰로 작성하는 방법을 알아본다. 이를 위해 기존 코드를 주석처리 한다.

#views.py > post_create

# def post_create(request):
#     if 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)
#         else:
#             context = {"post_form": post_form}
#     else:
#         post_form = PostForm()
#         context = {"post_form": post_form}
#     return render(request, 'posts/post_form.html', context=context)

1.1 클래스형 뷰 작성

기존의 함수형 뷰클래스형 뷰로 변경하기 위해서는 장고의 뷰 클래스상위 클래스상속 받아야 한다. 따라서 장고의 뷰 클래스를 불러온다.

#views.py

from django.views import View

이후 class를 생성하는데, 파스칼케이스 (Pascal Case) 관례를 따라서 언더바 없이 단어의 첫 글자를 대문자로 표기한다.

#views.py > PostCreateView

class PostCreateView(View):
    def get(self, request):
        post_form = PostForm()
        context = {"post_form": post_form}
        return render(request, 'posts/post_form.html', context=context)
    
    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)
        else:
            context = {"post_form": post_form}
            return render(request, 'posts/post_form.html', context=context)

코드를 살펴보면 장고의 View 클래스를 상위 클래스로 두어 상속받는다.

또한 함수형 뷰와는 달리 if문으로 요청방식이 POST일 때와 GET일 때를 구분하지 않아도 된다.

이는 상위 클래스인 장고의 View에서 요청이 들어오면 요청과 같은 이름의 함수를 실행하는 함수를 상속받았기 때문이다.


1.2 url 패턴 변경

url 패턴에서 post_create 뷰를 불러오는 방식을 PostCreateView를 불러오는 방식으로 변경한다.

이때 클래스형 뷰는 함수형 부를 불러오는 방법과는 다르게 뒤에 .as_view()를 사용해야 한다.

#urls.py

urlpatterns = [
    # path('', views.index),
    path('', views.post_list, name="post-list"),
    path('posts/new/', views.PostCreateView.as_view(), name="post-create"),
    path('posts/<int:post_id>/', views.post_detail, name="post-detail"),
    path('posts/<int:post_id>/edit/', views.post_update, name="post-update"),
    path('posts/<int:post_id>/delete/', views.post_delete, name="post-delete"),
]
profile
글로 쓰면 머리 속에 정리가 되...나?

0개의 댓글

관련 채용 정보