18

希望将我的项目更新到 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'),

我如何将类似的东西转换成这些新视图?

4

2 回答 2

31

通用视图迁移描述了基于类的视图替换了什么。根据文档,传递 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'),
于 2012-08-27T21:45:53.157 回答
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))
于 2013-09-27T17:41:47.387 回答