在 Django 中从 direct_to_template 移动到新的 TemplateView [英] Moving from direct_to_template to new TemplateView in Django

查看:17
本文介绍了在 Django 中从 direct_to_template 移动到新的 TemplateView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

与:

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆