Django View Layer

Introduction

  • A view is a type of Web page in your Django application that generally serves a specific function and has a specific template.
  • Every single view takes a request (and possibly other options) and returns an HttpResponse object.

Generic views

Django’s generic views take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.

Two similar views

def package_index(request):
    ps = Package.objects.order_by("name")
    return render_to_response("packages/index.html", {
        "package_list" : ps
 
def classifier_index(request):
    cs = Classifier.objects.order_by("name")
    return render_to_response("packages/classifiers.html", {
        "classifier_list" : cs
        })

Defining a generic view

def something_index(request, queryset, template):
    things = list(queryset)
    return render_to_response(template, {
        "thing_list" : cs
        })
 
def package_index(request):
    return something_index(
        queryset=Package.objects.all(), 
        template = "packages/index.html"
    )
 
def classifier_index(request):
    return something_index(
        queryset = Classifier.objects.all(), 
        template = "packages/classifiers.html"
    )

Using Generic Views

All of these views are used by creating configuration dictionaries in your URLconf files and passing those dictionaries as the third member of the URLconf tuple for a given pattern.

Functions

render_to_response

Example

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    t = loader.get_template('polls/index.html')
    c = Context({
        'latest_poll_list': latest_poll_list,
    })
    return HttpResponse(t.render(c))

It's a very common idiom to use get() and raise Http404 if the object doesn't exist. Django provides a shortcut.

from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})

get_object_or_404()

Example 1:Raising 404

from django.http import Http404
# ...
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})

Example 2: A shortcut to raising 404

from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})

get_list_or_404()

Shortcut function to be used in view functions for performing a filter() lookup and raising a Http404 exception if a DoesNotExist exception was raised during the filter() call.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.