LoginSignup
4
3

More than 3 years have passed since last update.

Djangoのクラスベースビュー

Posted at

はじめに

ここでは、djangoのクラスベースビュー(汎用ビュー)の基本について解説していきます。
アプリケーションディレクトリ下にあるviews.pyに書いていきます。
モデルとしてmodels.pySampleModelを、フォームとしてforms.pySampleFormを利用するものとします。

TemplateView

最もシンプルな形のクラスビューです。
いろいろなページの作成に使えます。

views.py
from django.views import generic


class SampleTemplate(generic.TemplateView):
    template_name = 'app/app_template.html'

なお、テンプレートとするHTMLファイルを指定するtemplate_nameは、アプリ名/アプリ名_view名.htmlとすると、クラス定義時に明示しなくてもデフォルトで利用されるようになります。以下で説明する他のビューでも同様です。

ListView

ブログの記事一覧ページなど、複数のレコードを一覧表示するページに使えます。

views.py
from django.views import generic

from .model import SampleModel


class SampleList(generic.ListView):
    model = SampleModel
    template_name = 'app/app_list.html'
    paginate_by = 10 # ページネーションを入れる場合

modelは、ページに表示するレコードを格納しているモデルを指定します。

CreateView

ブログの新規記事の作成など、新しいレコードを作成するページに使えます。

views.py
from django.urls import reverse_lazy
from django.views import generic

from .model import SampleModel
from .forms import SampleForm


class SampleCreate(generic.CreateView):
    model = SampleModel
    form_class = SampleForm
    template_name = 'app/app_create.html'
    success_url = reverse_lazy('app:app_list')

form_classで指定されたフォームに基づいて、フォーム画面が作成されます。
また、success_urlは、記事作成に成功した後に遷移するページを指定します。詳しくはurls.pyの記事で解説します。

DetailView

ブログの記事の個別ページなど、レコードの詳細を表示するページに使えます。

views.py
from django.views import generic

from .model import SampleModel
from .forms import SampleForm


class SampleDetail(generic.Detail):
    model = SampleModel
    template_name = 'app/app_detail.html'

UpdateView

ブログの記事の編集画面など、一度作成したレコード内容を更新するページに使えます。

views.py
from django.urls import reverse_lazy
from django.views import generic

from .model import SampleModel
from .forms import SampleForm


class SampleUpdate(generic.UpdateView):
    model = SampleModel
    form_class = SampleForm
    template_name = 'app/app_update.html'
    success_url = reverse_lazy('app:app_list')

DeleteView

ブログの記事の削除画面など、作成したレコードを削除するページに使えます。

views.py
from django.urls import reverse_lazy
from django.views import generic

from .model import SampleModel
from .forms import SampleForm


class SampleDelete(generic.DeleteView):
    model = SampleModel
    template_name = 'app/app_delete.html'
    success_url = reverse_lazy('app:app_list')

まとめ

ここでは、djangoのクラスベースビューの基本について解説しました。
次回は、関数ベースビューについて解説する予定です。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3