基于Django类的视图示例

时间:2014-05-16 13:09:14

标签: django django-views django-class-based-views class-based-views

我无法理解基于类的视图,所以我试图用一个例子来解决它。以下是我到目前为止的情况:

#urls.py
url(r'^(?P<langcode>[a-zA-Z-]+/about/$', about, name='about')


#views.py
def about(request, langcode):
    languages = Language.objects.values_list('code', flat=True)
    language = get_object_or_404(Language, pk=langcode)
    return render(request, 'about.html', {
        'languages': languages,
        'language': language
    })

我还有一些其他功能视图,其中包含about的前两行:

languages = Language.objects.values_list('code', flat=True)
language = get_object_or_404(Language, pk=langcode)

所以,我现在要做的是:

  1. 创建一个扩展的class BaseView(或者你想要调用它) 来自django.generic.views的内容,可根据language输入参数确定上下文的languageslangcode参数

  2. 创建class AboutView(BaseView)(扩展BaseView),以某种方式定义要用于渲染的模板名称about.html

  3. 我将进一步提供另一个基于类的视图,也可以将BaseView扩展为AboutView,但是它还会设置一个名为region的上下文参数。在langcode输入参数

  4. 有人能告诉我如何编码这些东西吗?谢谢

1 个答案:

答案 0 :(得分:2)

这是实现目标的简单方法:

首先使用TemplateView通用视图定义公共逻辑:

class MyBaseView(TemplateView):
    def dispatch(self, request, *args, **kwargs):
        # dispatch takes care of "reading" the parameters from the url
        self.language = get_object_or_404(Language, pk=kwargs.pop("langcode")) # I would use some kind of default value to prevent exception, but its up to your logic
        return TemplateView.dispatch(self, request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        # get_context_data creates the context
        context = TemplateView.get_context_data(self, **kwargs)
        context.update({"language": self.language, 
                        "languages": Language.objects.values_list('code', flat=True)})

        return context

然后,您甚至不需要AboutView,因为您只想控制template_name,所以在您的urls.py中:

# in urls,py you can just use this, instead of defining an AboutView, you pass the template_name you want to use, this is sufficient because TemplateView expects a template_name attribute
url('^(?P<langcode>[a-zA-Z]+)/about/$', MyBaseView.as_view(template_name="about.html"), name='about')

最后,对于使用region的其他视图,您可以从MyBaseView继承,并添加所需的上下文:

class AboutViewWithRegion(MyBaseView):
    def get_context_data(self, **kwargs):
        context = MyBaseView.get_context_data(self, **kwargs)
        context.update({"region": <<your logic here>>})
        return context

希望有所帮助!