본문 바로가기
Python/Django Ⅲ

(Review) Django CBV

by Mr.DonyStark 2024. 5. 27.

□ View 함수는 2가지로 나뉨

  ● CBV : Class Based View 

   ○ 클래스 기반 뷰

  ● FBV : Function Based View

    ○ 함수 기반 뷰

 

□ app > model 생성

from django.db import models

# Create your models here.
class Teacher(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    subject = models.CharField(max_length=30)

    def __str__(self):
        return f"{self.first_name} {self.last_name} teaches {self.subject}"

 

생성한 모델과 CBV 를 통해 자동으로 form 생성을 통해 데이터를 CRUD 해보자

  ● generic 으로 부터  TemplateView, FormView, CreateView, ListView, DetailView, UpdateView, DeleteView 임포트

  ● class ThankyouView(TemplateView)와 class ContactFormView(FormView) 는 app 내 별도 Form을 생성하여 코딩

  ● class TeacherCreateView(CreateView), class TeacherListView(ListView), class TeacherDetailView(DetailView), 

     class TeacherUpdateView(UpdateView), class TeacherDeleteView(DeleteView)는 뷰 자체에서 model을 바탕으로 form 생성 및 CRUD를 할 수 있는 클래스임

  ●  model_form.html 즉, teacher_form.html 형식으로 템플릿을 생성하면 자동으로 찾아서 매핑후 폼생성해줌

  ● reverse_lazy() : 앞에서의 메서드 및 기능 실행 후 반환되는 URL 지정 함수

from django.shortcuts import render
#reverse는 문자반환, reverse_lazy는 객체반환. 즉, reverse는 함수기반 reverse_lazy는 객체 반환
from django.urls import reverse, reverse_lazy
#cbv 생성을 위해 호출
from django.views.generic import TemplateView, FormView, CreateView, ListView, DetailView, UpdateView, DeleteView
from classroom.models import Teacher
from .forms import ContatctForm

# #fbv(function based view) : 함수기반뷰
# def home_view(request):
#     return render(request,"classroom/home.html")

class HomeView(TemplateView):
    template_name = "classroom/home.html"

class ThankyouView(TemplateView):
    template_name ="classroom/thank_you.html"

class ContactFormView(FormView):
    form_class = ContatctForm
    template_name ="classroom/contact.html"
    #url not a template.html : form이 성공적으로 POST 방식으로 전송되면 반환 url. 즉, 이동 url
    # success_url = "/classroom/thank_you/"
    success_url = reverse_lazy("classroom:thank")
    #what to do with form
    def form_valid(self,form):
        print(form.cleaned_data)
        print(form.cleaned_data["name"])        
        return super().form_valid(form)
    
class TeacherCreateView(CreateView):
    model = Teacher #모델생성
    #model_form.html teacher_form.html 형식으로 템플릿을 생성하면 자동으로 찾아서 매핑후 폼생성해줌
    fields = "__all__" #불러올 모델의 속성
    success_url = reverse_lazy("classroom:thank")
    # fields = ["first_name","last_name"]

class TeacherListView(ListView):
    #1.model생성
    #2.context_object_name 지정
    #3.queryset 오버라이드
    model = Teacher #model 을 지정하면 템플릿에서 object_list로 뿌릴수 있음
    context_object_name = "teacher_list" #object_list 말고 context_object_name 으로 템플릿에 뿌려줌
    # queryset = Teacher.objects.all()
    queryset = Teacher.objects.order_by("first_name")

class TeacherDetailView(DetailView):
    # model_dtail.html
    model = Teacher
    context_object_name = "OurtTeacher"
    # pk > {{teacher}}

class TeacherUpdateView(UpdateView):
    model=Teacher
    fields="__all__"
    success_url=reverse_lazy("classroom:list_teacher")

class TeacherDeleteView(DeleteView):
    #model_confirm_delete.html
    model = Teacher
    success_url = reverse_lazy("classroom:list_teacher")

 

URLS

from django.urls import path
from . import views
from . views import HomeView, ThankyouView, ContactFormView, TeacherCreateView, TeacherListView, TeacherDetailView, TeacherUpdateView, TeacherDeleteView

app_name = "classroom"

urlpatterns = [
    path("", HomeView.as_view(), name="home"), #path expath : function
    path("thank_you/", ThankyouView.as_view(), name="thank"),
    path("contact/", ContactFormView.as_view(), name="contact"),
    path("teacher/", TeacherCreateView.as_view(), name="teacher"),
    path("list_teacher/", TeacherListView.as_view(), name="list_teacher"),
    path("teacher_detail/<int:pk>", TeacherDetailView.as_view(),name="detail_teacher"),
    path("update_teacher/<int:pk>",TeacherUpdateView.as_view(),name="update_teacher"),
    path("delete_teacher/<int:pk>", TeacherDeleteView.as_view(), name ="delete_teacher")
]

 

Template

  ● teacher_list

<h1>List Of Teachers</h1>
<ul>
    {% for teacher in teacher_list %}
    <li>
        <a href="/classroom/teacher_detail/{{teacher.id}}">
            {{ teacher.first_name }} {{ teacher.last_name }}
        </a>
        <ul>
            <li>
                <a href="/classroom/update_teacher/{{teacher.id}}">
                    Update Info
                </a>
            </li>
            <li>
                <a href="/classroom/delete_teacher/{{teacher.id}}">
                    Delete Info
                </a>
            </li>
        </ul>
    
    </li>
    {% endfor %}
</ul>

 

  ● teacher_form

<h1>Teacher Form</h1>
<form method="POST">
    {% csrf_token %}    
    {{form.as_p}}
    <input type="submit" value="submit">
</form>

 

● teacher_detail

<h1>Detail View for a Teachers</h1>
<ul>
    {{OurtTeacher}}
</ul>

 

● teacher_confrim_delete

<h1>Are you sure you wanto to delete this teacher?</h1>
<h2>{{teacher}}</h2>
<form method="POST">
    {% csrf_token %}
    <input type="submit"value="confirm delete">
</form>