【まとめ】
①ListView: モデルの一覧表示。
②DetailView: オブジェクトの詳細表示。
③CreateView: オブジェクトの新規作成。
④UpdateView: 既存のオブジェクトを編集・更新。
⑤DeleteView: オブジェクトの削除。
⑥TemplateView: 静的なページを表示するのに便利。
⑦FormView:DBを使わないフォームを作成するのに便利
① ListView(一覧表示)
【目的】
・データベースのオブジェクトのリストを表示するために使います。
・指定したモデルの全データを自動的に取得し、テンプレートに `object_list` で渡し、オブジェクトのリスト表示を可能。
【処理の流れ】
1. URL設定にて `ListView` を割り当てます。
2. `get_queryset()` メソッドを使ってフィルタリングをカスタマイズできます。
3. `paginate_by` を指定すればページネーションもサポートされます。
4. `get_context_data()` を使ってテンプレートに追加データを渡すことができます。
【コード例】
URL
path('articles/', ArticleListView.as_view(), name='article_list')
View
from django.views.generic import ListView
from .models import Article
class ArticleListView(ListView):
model = Article
template_name = 'article_list.html'
context_object_name = 'articles'
paginate_by = 10
def get_queryset(self):
query = self.request.GET.get('q')
if query:
return Article.objects.filter(title__icontains=query)
return Article.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['search_query'] = self.request.GET.get('q', '')
return context
Template
{% for article in articles %}
<li>{{ article.title }}</li>
{% endfor %}
【備わっているメソッド】
・get_queryset()
・get_context_data(**kwargs)
・paginate_queryset(queryset, page_size)
・get_paginate_by(queryset)`
② DetailView(詳細表示)
【目的】
・単一のオブジェクトの詳細を表示するために使います。例えば、特定のユーザーのプロフィールや記事の詳細ページ。
・URLに含まれるIDを基にデータベースから特定のオブジェクトを取得し、それをテンプレートに渡します。
【処理の流れ】
1. get_object()で特定のオブジェクトを取得します。
2. get_context_data()を使って関連するデータ(例:コメント)をテンプレートに渡します。
3. カスタムロジックが必要な場合、`get_object()` メソッドをオーバーライドします。
【コード例】
URL
path('article/<int:pk>/', ArticleDetailView.as_view(), name='article_detail')
View
from django.views.generic import DetailView
from .models import Article, Comment
class ArticleDetailView(DetailView):
model = Article
template_name = 'articles/article_detail.html'
context_object_name = 'article'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.filter(article=self.object)
return context
Template
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
{% for comment in comments %}
<p>{{ comment.content }}</p>
{% endfor %}
【備わっているメソッド】
・get_object(queryset=None)
・get_context_data(**kwargs)
③ CreateView(新規作成)
【目的】
・モデルに基づいたフォームを自動生成し、入力されたデータを保存します。
【処理の流れ】
1. `form_class` にフォームを指定して、`form_valid()` を使ってバリデーションが成功したら保存します。
2. 保存前に追加の処理が必要な場合、`form_valid()` をオーバーライドしてカスタマイズします。
3. `get_context_data()` を使ってフォームに関連する追加情報をテンプレートに渡すことができます。
【コード例】
URL
path('article/new/', ArticleCreateView.as_view(), name='article_create')
View
from django.views.generic import CreateView
from .models import Article
from .forms import ArticleForm
from django.urls import reverse_lazy
class ArticleCreateView(CreateView):
model = Article
form_class = ArticleForm
template_name = 'articles/article_form.html'
success_url = reverse_lazy('articles:article_list')
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Create New Article'
return context
Template
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
【備わっているメソッド】
・get_form_class()
・get_form_kwargs()
・form_valid(form)
・form_invalid(form)
・get_context_data(**kwargs)
・get_success_url()
④ UpdateView(更新)
【目的】
・既存のデータをフォームに表示し、ユーザーが編集した内容を保存します。
【処理の流れ】
1. get_object()で対象オブジェクトを取得。
2. form_valid()でバリデーションが通ったら保存されます。
3. get_context_data()を使って、テンプレートに追加データを渡すことができます。
【コード例】
URL
path('article/<int:pk>/edit/', ArticleUpdateView.as_view(), name='article_update')
View
from django.views.generic import UpdateView
from .models import Article
from .forms import ArticleForm
from django.urls import reverse_lazy
from django.http import Http404
class ArticleUpdateView(UpdateView):
model = Article
form_class = ArticleForm
template_name = 'articles/article_form.html'
success_url = reverse_lazy('articles:article_list')
def get_object(self, queryset=None):
obj = super().get_object(queryset)
if obj.author != self.request.user:
raise Http404("You are not allowed to edit this article.")
return obj
def form_valid(self, form):
form.instance.editor = self.request.user
return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Update Article'
return context
【備わっているメソッド】
・get_object()
・get_form_class()
・get_form_kwargs()
・form_valid(form)
・form_invalid(form)
・get_context_data(**kwargs)
⑤ DeleteView(削除)
【目的】
・削除の確認ページを表示し、ユーザーが確認した後にオブジェクトを削除します。
【処理の流れ】
1. get_object()で対象オブジェクトを取得。
2. delete()メソッドが呼ばれ、オブジェクトが削除されます。
3. get_context_data()を使って、削除確認ページに関連するデータを渡します。
【コード例】
URL
path('article/<int:pk>/delete/', ArticleDeleteView.as_view(), name='article_delete')
View
from django.views.generic import DeleteView
from .models import Article
from django.urls import reverse_lazy
from django.http import Http404
from django.contrib import messages
class ArticleDeleteView(DeleteView):
model = Article
template_name = 'articles/article_confirm_delete.html'
success_url = reverse_lazy('articles:article_list')
def get_object(self, queryset=None):
obj = super().get_object(queryset)
if obj.author != self.request.user:
raise Http404("You are not allowed to delete this article.")
return obj
def delete(self, request, *args, **kwargs):
messages.success(self.request, "Article deleted successfully.")
return super().delete(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Confirm Delete'
return context
【備わっているメソッド】
・get_object()
・delete(request, *args, **kwargs)
・get_success_url()
・get_context_data(**kwargs)
⑥ TemplateView(静的ページ)
【目的】
・シンプルな静的ページ(例えば、ホームページやお知らせページ)を表示するために使います。
・テンプレートだけをレンダリングするのが主な機能で、特別なロジックを必要としない場合に便利です。
【処理の流れ】
1. `get_context_data()` を使ってテンプレートに動的なデータを渡します。
【コード例】
URL
path('about/', TemplateView.as_view(template_name='about.html'), name='about')
View
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Welcome to Our Website'
return context
【備わっているメソッド】
・get_template_names()
・get_context_data(**kwargs)
⑦ FormView(フォーム処理)
【目的】
・DBに保存しないカスタムフォーム(例えば、問い合わせフォームやフィードバックフォーム)に使用する。
・モデルに依存しないフォームを処理し、`POST` リクエストを処理する場合に便利です。
【処理の流れ】
1. form_class にフォームを指定して、form_valid() を使ってバリデーションが成功したら処理を行います。
2. フォーム送信後にメールを送信したり、外部サービスと連携します。
3. get_context_data()を使ってフォームに関連する情報をテンプレートに渡します。
【コード例】
URL
path('contact/', ContactView.as_view(), name='contact')
View
from django.views.generic.edit import FormView
from .forms import ContactForm
from django.urls import reverse_lazy
from django.core.mail import send_mail
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = reverse_lazy('contact_success')
def form_valid(self, form):
# フォームのデータを使ってメールを送信
send_mail(
form.cleaned_data['subject'],
form.cleaned_data['message'],
form.cleaned_data['email'],
['admin@example.com']
)
return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form_title'] = 'Contact Us'
return context
Template
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
【備わっているメソッド】
・get_form_class()
・get_form_kwargs()
・form_valid(form)
・form_invalid(form)
・get_context_data(**kwargs)
・get_success_url()