我正在尝试使用 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 响应。
这是我的看法:
视图.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>