Django Generic Views Minimum Example: Functional vs. Generic Views


Example for a functional view to create an object. Excluding comments and blank lines, we need 15 lines of code:

# imports
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

from .models import SampleObject
from .forms import SampleObjectForm

# view functioon
def create_object(request):
    # when request method is 'GET', show the template
    if request.method == GET:
        # perform actions, such as loading a model form
        form = SampleObjectForm()
        return render_to_response('template.html', locals())
    # if request method is 'POST', create the object and redirect
    if request.method == POST:
        form = SampleObjectForm(request.POST)

        # save object and redirect to success page if form is valid
        if form.is_valid:
            return HttpResponseRedirect('url_to_redirect_to')

        # load template with form and show errors
            return render_to_response('template.html', locals())

Example for a 'Class-Based Generic View' to perform the same task. We only need 7 lines of code to achieve the same task:

from django.views.generic import CreateView

from .models import SampleObject
from .forms import SampleObjectForm

class CreateObject(CreateView):
    model = SampleObject
    form_class = SampleObjectForm
    success_url = 'url_to_redirect_to'