diadia

興味があることをやってみる。自分のメモを残しておきます。

get_object_or_404 detailページにつけるやり方

全然分かってないのでメモ。
ドキュメント
https://docs.djangoproject.com/ja/2.0/topics/http/shortcuts/#get-object-or-404

Calls get() on a given model manager, but it raises Http404 instead of the model's DoesNotExist exception.
引数はklass, **kwargsのふたつ

renderを使ってページを表示させる場合には以下のように処理したいた。
views.py

from django.shortcuts import render

def test(request, pk):
    object = Product.objects.get(id=pk)
    context = {"object": object}
    render(request, 'TEST/test.html', context ) 

こんな感じで、必要なpkをrequestに追加して書くことでほしいデータの詳細ページを表示させる事ができる。

get_object_or_404を使うとobject = test.objects.get(pk=pk)という一文の機能も兼ねることになるので、その一文は書かなくて良い。



views.py にて

from django.shortcuts import render, get_object_or_404
def product_detail_view(request, pk):
    object = get_object_or_404(klass , pk=pk)
    context = {"object": object}
    render(request, 'TEST/test.html', context ) 


このやり方の他にHttp404を使う方法でも404エラーを表示できることがわかった。上の方法よりどうしてエラーが出たのかわかりやすくなったと思う。

from django.http import Http404
from django.shortcuts import render


def product_detail_view(request,pk)

    try:
        instance = Product.objects.get(pk=pk)
    except Product.DoesNotExist:
        print("no product here")
    except:
        print("?")

    context = {"object":instance}  
return render(request, "TEST/test.html",context)


もっとデータベースからwebページを表示させてる感を出すには以下の方法を取る。

def product_detail_view(request, pk)
    queryset = Product.objects.filter(id=pk)
    if queryset.exist() and queryset.count() ==1:
        instance = queryset.first()