Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

generics - Moving from direct_to_template to new TemplateView in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Using this class you would replace:

(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'),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...