通用视图迁移描述了基于类的视图替换了什么。根据文档,传递 extra_context 的唯一方法是继承 TemplateView 并提供您自己的 get_context_data 方法。这是我想出的一个 DirectTemplateView 类,它允许extra_context
使用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
使用此类,您将替换:
(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'),
和:
(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'),