Django Generic Views Customizing Generic Views


The above example only works if your tasks are entirely standard tasks. You do not add extra context here, for example.

Let's make a more realistic example. Assume we want to add a page title to the template. In the functional view, this would work like this - with just one additional line:

def create_object(request):
    page_title = 'My Page Title'

    # ...

    return render_to_response('template.html', locals())

This is more difficult (or: counter-intutitive) to achieve with generic views. As they are class-based, you need to override one or several of the class's method to achieve the desired outcome. In our example, we need to override the class's get_context_data method like so:

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

    def get_context_data(self, **kwargs):
        # Call class's get_context_data method to retrieve context
        context = super().get_context_data(**kwargs) 
        context['page_title'] = 'My page title'
        return context

Here, we need four additional lines to code instead of just one - at least for the first additional context variable we want to add.