18

私のプロジェクトを最新バージョンの django に更新しようとしていますが、一般的なビューがかなり変更されていることがわかりました。ドキュメントを見ると、すべての一般的なものがクラスベースのビューに変更されていることがわかります。ほとんどの使用方法は理解していますが、ビューに対してより多くのオブジェクトを返すときに何をする必要があるかについて混乱しています。現在の URL は次のようになります。

(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

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'),
于 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 に答える