[Django] FBV vs CBV

형이·2023년 11월 14일

Python

목록 보기
27/34
post-thumbnail

📝 FBV vs CBV

🖥️ 1. FBV

  • 함수형 뷰 Function Based View
  • URL 패턴에 대한 요청을 처리하기 위해 함수를 사용하는 뷰
  • 장고의 기본적인 뷰 방식 중 하나고, 간단한 애플리케이션에서 사용
urls.py

urlpatterns=[
	path('', views.index),
]
views.py

def index(request):
	posts = Post.objects.all().order_by('-pk')
	return render(request, 'blog/post_list.html', {'abc' : posts})

🖥️ 2. CBV

  • 클래스형 뷰 Class Bassed View
  • URL 패턴에 대한 요청을 처리하기 위해 클래스를 사용하는 뷰이다.
  • FBV와는 달리 클래스로 구현되므로, 좀 더 복잡한 애플리케이션에서 유용하게 사용될 수 있다.
urls.py

urlpatterns=[
	path('', views.PostList.as_view()),
]
views.py

class PostList(ListView):
    # ListView : model 속성에 어떤 모델의 데이터를 보여줄지 작성
    #            model_list.html 화면 기본값
    #            model_list 변수를 사용해서 템플릿에서 객체 리스트 엑세스

    # template_name = 'blog/post_list.html'
    # context_object_name = 'abc'
    model = Post
    ordering = '-pk'

    def get_context_data(self, **kwargs):
        # 부모 클래스의 get_context_data()를 호출, 딕셔너리
        context = super(PostList, self).get_context_data()
        # categories라는 키를 가진 context 딕셔너리에 모든 Category 객체를 값으로 추가
        context['categories'] = Category.objects.all()
        context['no_category_post_count'] = Post.objects.filter(category=None).count()
        return context

2-1. List

  • 조건에 맞는 객체 목록 출력

2-2. DetailView

  • 조건에 맞는 하나의 객체를 출력
class PostDetail(DetailView):
    model = Post
    # template_name = 'blog/post_detail.html'  # 모델_detail.html
    # post 변수를 사용해서 템플릿에서 객체 접근 가능

    def get_context_data(self, **kwargs):
        context = super(PostDetail, self).get_context_data()
        context['categories'] = Category.objects.all()
        context['no_category_post_count'] = Post.objects.filter(category=None).count()
        return context

2-3. CreateView

  • 객체를 생성하는 폼 출력
class PostCreate(CreateView):
    model = Post
    # Post의 필드에서 어떠한 것들을 정할 것인지
    fields = ['title', 'hook_text', 'content', 'head_image', 'file_upload', 'category']

2-4. UpdateView

  • 기존 객체를 수정하는 폼을 출력

2-5. DeleteView

  • 기존 객체를 삭제하는 폼을 출력

2-6. TemplateView

  • 주어진 템플릿으로 렌더링

2-7. FormView

  • 커스텀 폼을 표시하는 화면을 반환

0개의 댓글