Django – View generic

ListView

주로 목록을 나타낼 때 사용한다.
views.py

from django.views.generic import ListViev
class Categories(ListView):
    model = Category
    template_name = 'manager/categories_list.html'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

model – 불러올 데이터 모델
template_name – 템플릿 경로
get_context_data(self, **wargs) –
사용자에게 보여지기 전, 클래스가 생성되고 해당 데이터들을 받아 수정할 수 있는 함수이다.
이곳에서 데이터를 담아 보낼 수 있다.
views.py

from django.views.generic import ListViev
class Categories(ListView):
    model = Category
    template_name = 'manager/categories_list.html'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user'] = self.user
        return context

context[] 사이에 템플릿에서 사용할 이름을 적고 해당 공간에 값을 넣어주면 된다.

FormView

FormView는 폼에 특화되어 있어서 form.py에서 생성한 폼을 이용한다면 해당 클래스를 사용하는 것도 좋다.
forms.py

class RegisterCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = '__all__'
        widgets = {
            'parent':forms.Select(
                attrs={'class': 'form-control',
                      'id': 'sel1',
                        'placeholder': '입력하세요'
                }),
            'name':forms.TextInput(
                attrs={'class': 'form-outline',
                      'id': 'textAreaExample6',
                        'placeholder': '입력하세요'
                }),
            'slug': forms.TextInput(
                attrs={'class': 'form-outline',
                      'id': 'textAreaExample6',
                        'placeholder': '입력하세요'
                })
        }
        def clean(self):
                cleaned_data = super().clean()
                name = cleaned_data.get('name')
                slug = cleaned_data.get('slug')
                description = cleaned_data.get('description')

views.py

from django.views.generic.edit import FormView
class Categories_Register(FormView):
    template_name = 'manager/categories_register.html'
    form_class = RegisterCategoryForm
    success_url = reverse_lazy('manager:categories')
    def form_valid(self, form):
        form.save()
        return redirect('manager:categories')

success_url – 해당 작업들이 완료된 후 이동할 URL를 작성한다.
form_valid(self,form) –
폼이 생성되고 사용자가 작성 후 이벤트를 발생시켜 폼이 다시 뷰에서 폼내용이 확인이 되면 해당 함수가 실행된다. 주로 CUD,(Create, Upate,Delete)에 사용한다.

DetailView

하나의 pk값을 받아와 조회하여 사용자에게 보여주기 위한 목적에 특화되어 있는 듯 하다.
views.py

from django.views.generic import DetailView
class ProductDetailView(DetailView):
    template_name = "product/product_detail.html"
    queryset = Product.objects.all()
    context_object_name = 'product'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

queryset – 페이지에 보여줄 데이터 쿼리를 작성한다.

DeleteView

pk 값을 받아와 데이터를 삭제할 때 사용한다.
views.py

from django.views.generic import DeleteView
class ProductDeleteView(DeleteView):
    model = Product
    success_url = '/product'

Leave a Comment