LoginSignup
3
0

More than 5 years have passed since last update.

(個人用)Djangoチュートリアルその2:django.shortcuts

Last updated at Posted at 2019-04-17

1. render(request, テンプレート, コンテキスト)

polls/views.py
from django.http import HttpResponse
from django.template import loader

def index(request):
    (中略)
    template = loader.get_template('polls/index.html')
    return HttpResponse(template.render(context, request))

django.http.HttpResponse, django.template.loaderの代わりに、
django.shortcuts.renderを利用することでコンパクトに記述可能。

polls/views.py
from django.shortcuts import render
# ...
def index(request):
    (中略)
    return render(request, 'polls/index.html', context)

2. get_object_or_404(オブジェクト, pk)

polls/views.py
from django.http import Http404
from django.shortcuts import render

from .models import Question
# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

django.http.Http404の代わりに、django.shortcuts.get_object_or_404をインポート。
try~except文を用いた分岐を用いなくても良いので、よりコンパクトな記述が可能となる。

polls/views.py
from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

ちなみに、
get_list_or_404()
という関数もあるそうです。
この関数は
get_object_or_404()
と同じように動きますが、
get() ではなく、 filter() を使います。

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