[Fixed]-Moving from direct_to_template to new TemplateView in Django

31👍

Generic Views Migration describes what class based view replaces what. According to the doc, the only way to pass extra_context is to subclass TemplateView and provide your own get_context_data method. Here is a DirectTemplateView class I came up with that allows for extra_context as was done with direct_to_template.

from django.views.generic import TemplateView

class DirectTemplateView(TemplateView):
    extra_context = None
    def get_context_data(self, **kwargs):
        context = super(self.__class__, self).get_context_data(**kwargs)
        if self.extra_context is not None:
            for key, value in self.extra_context.items():
                if callable(value):
                    context[key] = value()
                else:
                    context[key] = value
        return context

Using this class you would replace:

(r'^$', direct_to_template, { 'template': 'index.html', 'extra_context': { 
    'form': CodeAddForm, 
    'topStores': get_topStores, 
    'newsStories': get_dealStories, 
    'latestCodes': get_latestCode, 
    'tags':get_topTags, 
    'bios':get_bios
}},  'index'),

with:

(r'^$', DirectTemplateView.as_view(template_name='index.html', extra_context={ 
    'form': CodeAddForm, 
    'topStores': get_topStores, 
    'newsStories': get_dealStories, 
    'latestCodes': get_latestCode, 
    'tags':get_topTags, 
    'bios':get_bios
}), 'index'),
👤Pykler

4👍

I ran into a problem with Pykler’s answer using the DirectTemplateView subclass. Specifically, this error:

AttributeError at /pipe/data_browse/ 'DirectTemplateView' object has no attribute 'has_header' Request Method:  
  GET Request URL:  http://localhost:8000/pipe/data_browse/ Django Version: 1.5.2
  Exception Type:   AttributeError
  Exception Value:   'DirectTemplateView' object has no attribute 'has_header'
  Exception Location:   /Library/Python/2.7/site-packages/django/utils/cache.py in patch_vary_headers, line 142 
  Python Executable:    /usr/bin/python 
  Python Version:   2.7.2

What worked for me was to instead convert any line like this:

return direct_to_template(request, 'template.html', {'foo':12, 'bar':13})

to this:

return render_to_response('template.html', {'foo':12, 'bar':13}, context_instance=RequestContext(request))
👤Dylan

Leave a comment