首页 > 解决方案 > 从基于类的视图中的 HTTP 方法返回响应对象

问题描述

class BaseListView(MultipleObjectMixin, View):
    """A base view for displaying a list of objects."""
    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        allow_empty = self.get_allow_empty()

        if not allow_empty:
            # When pagination is enabled and object_list is a queryset,
            # it's better to do a cheap query than to load the unpaginated
            # queryset in memory.
            if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
                is_empty = not self.object_list.exists()
            else:
                is_empty = not self.object_list
            if is_empty:
                raise Http404(_('Empty list and “%(class_name)s.allow_empty” is False.') % {
                    'class_name': self.__class__.__name__,
                })
        context = self.get_context_data()
        return self.render_to_response(context)

所以我从文档中获取了这段代码,我对 render_to_response() 方法很感兴趣,我已经阅读过,我相信它构造了一个指定的响应类(templateReponseMixin.response_class 属性)或默认响应类(TemplateResponse 类)的实例),比我更有经验的人能否告诉我 Response 实例是否也在 render_to_response() 方法中呈现并返回,还是由另一个中间件代码呈现?

标签: django

解决方案


与您的问题相关的两件事:

  1. 似乎您忘记将模板传递给此方法。是签名。是的,它会通过调用模板加载器模块的render_to_string来渲染模板。基本上唯一的区别是将对象传递到模板上下文中,而此方法不是。renderrequest
  2. 如果您从头开始项目,我认为您可能不会为 render_to_response 烦恼,因为它自 v2.0 以来已被弃用

推荐阅读