在Django中从direct_to_template移动到新的TemplateView [英] Moving from direct_to_template to new TemplateView in Django
问题描述
希望将我的项目更新到最新版本的django,并发现通用视图已经发生了很大变化。看看文档我看到他们把所有的泛型都改成了基于类的视图。我了解大部分的用法,但是当返回一个视图的大量对象时,我感到困惑。当前的网址可能如下所示:
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?
推荐答案
通用视图迁移描述了基于什么类的视图替代了什么。根据该文档,传递extra_context的唯一方法是将TemplateView子类化并提供您自己的get_context_data方法。这是一个DirectTemplateView类,我想出了允许 extra_context
与 direct_to_template
一样。
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
使用此类可以替换:
(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'),
这篇关于在Django中从direct_to_template移动到新的TemplateView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!