0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ECサイト作成で学んだこと④

Posted at

今回はECサイトを作成で学んだことを4つに分けて記事にしていきます。

以下の箇条書きの記事をそれぞれ作成します。
記事が出来次第、リンクへ変更になりますのでお待ちください。

  • エンジニアリングについて
  • Djangoについて
  • Pythonの文法
  • 汎用ビューについて

汎用ビューについて

基礎的な部分の説明は省きます。

  • post()メソッド
  • get_context_data()メソッド
  • get_queryset()メソッド

post()メソッド

post()は、フォームのPOSTリクエストを処理するために使用します。

実装例(カートへの商品追加)

from django.views import View
from django.shortcuts import redirect, get_object_or_404
from django.contrib import messages

class AddToCartView(View):
    def post(self, request, product_id):
        form = AddToCartForm(request.POST)
        if not form.is_valid():
            messages.error(request, form.errors["num"][0])
            return redirect("cart:cart_page")
        
        cart = Cart.get_or_create_cart(request)
        product = get_object_or_404(Product, id=product_id)
        cart.add_product(product, form.cleaned_data["num"])
        messages.success(request, f'{product.name}をカートに追加しました')
        return redirect(request.META.get("HTTP_REFERER", "cart:cart_page"))
  • request.POSTからデータを取得し、フォームバリデーションを行う
  • 処理後にredirect()を使って適切なページへリダイレクトする(RPGパターン)
  • エラーメッセージをmessagesに保存し、リダイレクト後に出力可能にする

get_context_data() メソッド

get_context_data()は、テンプレートに渡すデータをカスタマイズしたい時に使用します。

実装例(カートの情報を取得)

class CartPageView(ListView):
    template_name = 'cart/cart_page.html'
    model = CartProduct

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        cart = Cart.get_or_create_cart(self.request)
        cart_products = cart.cart_products.select_related("product")
        
        context["cart_products"] = cart_products
        context["total_cart_price"] = sum(p.sub_total_price() for p in cart_products)
        context["total_quantity"] = sum(p.quantity for p in cart_products)
        return context
  • super().get_context_data(**kwargs)で親クラスのデフォルトコンテキストを取得
  • 追加のデータ(cart_products, total_cart_priceなど)をcontextに格納
  • テンプレート内でデータを簡単に参照できるようにする

get_queryset() メソッド

get_queryset()は、ビューで取得するデータのクエリセットをカスタマイズしたい時に使用します。

実装例(登録済みの商品一覧の取得)

class ProductListView(ListView):
    model = Product

    def get_queryset(self):
        return Product.objects.filter(is_published=True)  # 公開済みの商品だけ取得
  • デフォルトのmodel.objects.all()filter()で絞り込むことができる
  • 条件付きのデータ取得(例えばis_published=Trueのみ)を簡単に設定可能
  • select_related()を追加してパフォーマンス向上も可能

どのクラスを継承するか問題

よし、modeltemplate_nameはわかったけどどのクラスを継承したらいいのかわからないという状況になったので、表を用いて説明します。

目的 適切なCBV 説明
単純なページ表示 TemplateView ただの静的ページ(HP, 利用規約)
データ一覧の表示 ListView モデルのリストを取得し、テンプレートに渡す
(商品一覧、注文履歴など)
詳細ページの表示 DetailView 特定のオブジェクトの詳細を表示
(商品詳細、注文詳細
フォームを含むページ FormView フォームのバリデーションや処理が必要
(と言わせフォーム、注文フォーム)
データの作成 CreateView モデルの新規作成
(商品登録、ユーザー登録)
データの更新 UpdateView モデルのデータを編集
(プロフィール編集、商品情報編集)
データの削除 DeleteView モデルのデータを削除
(アカウント削除、注文キャンセル)
特殊な処理
(GET/POST)
View 複数のフォーム処理やカスタムロジックが必要な場合

最後に

今回はECサイト作成で学んだこと④ということで
汎用ビューについて記載しました。

説明不足やもっと必要なことがあるかもしれませんが
その都度書き足していきます!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?