Today I Learned/django

장고 generic display view 로 간단하게 bookmark앱 구현하기

하나719 2023. 6. 28. 18:08
반응형

장고에서 뷰 로직을 함수형 (def) 또는 클래스형 (class) 으로 정의할 수 있다.

이 때 클래스형으로 정의하면 장고에서 제공하는 제네릭 뷰를 활용할수 있는 장점이 있다. 

 

Generic View 종류

  1. Base View
    - View : 최상위에 있는 부모 제네릭 뷰 클래스
    - Template View : 주어진 템플릿으로 렌더링해주는 뷰
    - Redirect View : 주어진 URL로 Redirect해주는 기능의 뷰
  2. Generic Display View
    - ListView : 조건에 맞는 객체들의 목록을 보여주는 뷰
    - DetailView : 조건에 맞는 하나의 세부 객체들을 보여주는 뷰

  3. Generic Edit View
    - FormView : 폼이 주어지면 해당 폼을 출력하는 뷰
    - CreateView : 새로운 객체를 폼을 출력하는 뷰
    - UpdateView : 기존의 객체를 수정하는 폼을 출력하는 뷰
    - DeleteView : 기존에 있는 객체를 삭제하는 폼을 출력하는 뷰

  4. Generic Date View
    - YearArchiveView : 주어진 연도에 해당하는 객체를 모아줌
    - MonthArchiveView : 주어진 월에 해당하는 객체를 모아줌
    - DayArchiveView : 주어진 날짜에 해당하는 객체를 모아줌
    - TodayArchiveView : 오늘 날짜에 해당하는 객체를 모아줌
    - DateDetailView : 특정한 연, 월, 일 등에 해당하는 객체를 모아줌

가장 기본적인 ListView와 DetailView를 사용하면 간단하게 데이터의 목록과 데이터상세 화면을 구현할 수 있다.

 

구현할 화면

리스트화면에서 특정 데이터를 클릭하면 개별화면으로 이동하는 간단한 앱 구현

ListView
DetailView

1. model 만들기

title과 url 두가지 컬럼을 가지는 모델이며, title을 return 해준다. 

from django.db import models

# Create your models here.

class Bookmark(models.Model):
    title = models.CharField('TITLE',max_length=100,blank=True)
    url = models.URLField('URL', unique=True)

    def __str__(self):
        return self.title

2. View 만들기 (Generic View 활용)

context_object_name -> templates에서 받아올 object 변수명

template_name -> template 경로 

BookmarkLV 클래스에서는 위에 두가지를 지정해주었는데 생략 가능하다.

generic view를 사용하면 따로 입력해주지 않아도 자동으로 생성해주기 때문이다. 대신 정해진 규칙대로 사용해야한다.

 

ListView

- context_object_name: object_list

- templates 파일명: xxxx_list.html -> xxxxxx_list.html으로 생성해주면 자동으로 매핑해준다. 

DetailView

- context_object_name:object

- templates 파일명: xxxx_detail.html

from django.views.generic import ListView, DetailView
from bookmark.models import Bookmark


# Create your views here.
class BookmarkLV(ListView):
    model = Bookmark
    context_object_name = 'bookmarks'
    template_name = 'bookmark/bookmark_list.html'

class BookmarkDV(DetailView):
    model = Bookmark

3. template 생성

bookmark_list.html

context_object_name명을 bookmarks로 지정해주었기때문에 for문에서 bookmarks로 받아와서 사용했는데 만약 지정해주지 않았다면 object_list 로 사용해주면 된다. 

<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Bookmark</title>
</head>
<body>
    <h1>Bookmark List</h1>
    <ul>
        {% for bookmark in bookmarks %}
        <li><a href="{% url 'detail' bookmark.id %}">{{ bookmark }}</a> </li>
        {% endfor %}
    </ul>
</body>
</html>

bookmark_detail.html

context_object_name명을 지정해주지 않았는데 코드에서 object로 자동으로 받아와서 작성해주었다. 

<!doctype html>
<html lang='ko'>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>bookmark detailview</title>
</head>
<body>
<h1> {{ object.title }} </h1>
<ul>
    <li>URL <a href="{{object.url}}">{{object.url}}</a> </li>
</ul>
</body>
</html>

4. urls.py

bookmark 앱 아래 urls.py 파일을 따로 생성해서 정리해서 bookmark/는 생략했다.

클래스형 함수로 뷰를 구현했으므로, as_view()로 불러와준다. 

 

참고: 2023.06.28 - 장고 앱 url 분리작성하기

from django.urls import path
from .views import BookmarkLV, BookmarkDV

urlpatterns = [
    path('',BookmarkLV.as_view(), name ='index'),
    path('<int:pk>/',BookmarkDV.as_view(), name = 'detail'),
]

 

반응형