Skip to content

django


django shortcuts

render()

#this generates the template object and renders it with the context
#behind the scenes
render(http_request, template_name, context)


from django.shortcuts import render

from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

get_object_or_404() or get_list_or_404()

#passes the kwargs to the get() function of the model manager
get_object_or_404(model, kwargs)

#passes kwargs to the filter() function instead of get()
get_list_or_404(model, kwargs)


from django.shortcuts import get_object_or_404, render

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

See also