Looking to update my project to the latest version of django and have found that generic views have changed quite a bit. Looking at the documentation I see that they changed all the generic stuff to class based views. I understand the usage for the most part, but am confused as to what I need to do when returning a larger number of objects for a view. A current url might look like :
(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'),
How do I convert something like that into these new views?
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'),
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With