📝 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
- URL 패턴에 대한 요청을 처리하기 위해 클래스를 사용하는 뷰이다.
- FBV와는 달리 클래스로 구현되므로, 좀 더 복잡한 애플리케이션에서 유용하게 사용될 수 있다.
urls.py
urlpatterns=[
path('', views.PostList.as_view()),
]
views.py
class PostList(ListView):
model = Post
ordering = '-pk'
def get_context_data(self, **kwargs):
context = super(PostList, self).get_context_data()
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
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
fields = ['title', 'hook_text', 'content', 'head_image', 'file_upload', 'category']
2-4. UpdateView
2-5. DeleteView
2-6. TemplateView