希望将我的项目更新到最新版本的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'),
如何将这样的内容转换为这些新视图?
答案 0 :(得分:29)
Generic Views Migration描述了基于类的视图取代了什么。根据文档,传递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'),
答案 1 :(得分:4)
我使用DirectTemplateView子类遇到了Pykler答案的问题。具体来说,这个错误:
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
对我来说有用的是转换任何这样的行:
return direct_to_template(request, 'template.html', {'foo':12, 'bar':13})
到此:
return render_to_response('template.html', {'foo':12, 'bar':13}, context_instance=RequestContext(request))