Django Braces的“JSONResponseMixin”表现出奇怪的行为

时间:2013-08-13 07:27:20

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

我正在尝试使用Django-braces包中的“JSONResponseMixin”。

混音:

class JSONResponseMixin(object):
    """
    A mixin that allows you to easily serialize simple data such as a dict or
    Django models.
    """
    content_type = u"application/json"
    json_dumps_kwargs = None

    def get_content_type(self):
        if self.content_type is None:
            raise ImproperlyConfigured(
                u"%(cls)s is missing a content type. "
                u"Define %(cls)s.content_type, or override "
                u"%(cls)s.get_content_type()." % {
                u"cls": self.__class__.__name__}
            )
        return self.content_type

    def get_json_dumps_kwargs(self):
        if self.json_dumps_kwargs is None:
            self.json_dumps_kwargs = {}
        self.json_dumps_kwargs.setdefault(u'ensure_ascii', False)
        return self.json_dumps_kwargs

    def render_json_response(self, context_dict, status=200):
        """
        Limited serialization for shipping plain data. Do not use for models
        or other complex or custom objects.
        """
        json_context = json.dumps(context_dict, cls=DjangoJSONEncoder,
                                  **self.get_json_dumps_kwargs())
        return HttpResponse(json_context,
                            content_type=self.get_content_type(),
                            status=status)

    def render_json_object_response(self, objects, **kwargs):
        """
        Serializes objects using Django's builtin JSON serializer. Additional
        kwargs can be used the same way for django.core.serializers.serialize.
        """
        json_data = serializers.serialize(u"json", objects, **kwargs)
        return HttpResponse(json_data, content_type=self.get_content_type())

我基本上将这个mixin继承到我自己的视图中,以返回对javascript回调函数的JSON响应。

以下是我的观点:

views.py

class PostDetail(JSONResponseMixin, DetailView):
    model = Post
    template_name = 'post_detail_page.html'

所以这是一个非常简单的视图......但是当我打开这个视图时,会发生奇怪的事情。该页面显示简单的html源代码,而不是将源呈现为html页面。当然,一旦我在视图中删除了JSONResponseMixin继承,就不会发生这种情况。我不知道为什么会发生这种情况,因为JSONResponseMixin不直接覆盖“render_to_response”方法或任何重要的方法....

有人能告诉我为什么会这样吗......?感谢!!!

顺便说一句,这是生成的html页面:

<html>
    <head>
        <link title="Wrap Long Lines" href="resource://gre-resources/plaintext.css" type="text/css" rel="alternate stylesheet">
        #HAVE NO IDEA WHERE THIS CAME FROM...
    </head>

    <body>
        #ALL MY HTML SOURCE CODE APPEARS HERE WITHOUT BEING RENDERED!!!
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

content_type = u"application/json"

此行实际上由DetailView使用。我最好的猜测是,这搞砸了模板的渲染;使用"application/json"或不提供字符集。

我会单独保留默认的content_type(使用content_type = None)并覆盖get_content_type以提供使用Ajax时所需的内容类型。

要将JSON完全合并到您的视图中,您可能应该在render_to_response视图上覆盖PostDetail

class PostDetail(JSONResponseMixin, DetailView):
    model = Post
    template_name = 'post_detail_page.html'
    content_type = None

    def render_to_response(self, **kwargs):
        if self.request.is_ajax():
            # Don't really know if objects will take a list, a queryset, any iterable or even a single object
            return self.render_json_object_response(objects=[self.object]):
        else:
            return super(PostDetail, self).render_to_response(**kwargs)

    def get_content_type(self):
        if self.request.is_ajax():
            return u'application/json'
        else:
            return None