一尘不染

在Django中从direct_to_template移到新的TemplateView

django

希望将我的项目更新为django的最新版本,并且发现通用视图已经发生了很大变化。查看文档,我发现他们将所有通用内容更改为基于类的视图。我大部分时候都了解用法,但是对于为视图返回大量对象时我该怎么办感到困惑。当前网址可能类似于:

(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'),

如何将类似的内容转换为这些新视图?


阅读 502

收藏
2020-04-03

共1个答案

一尘不染

传递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'),
2020-04-03