【问题标题】:Json response list with django带有 django 的 Json 响应列表
【发布时间】:2014-11-15 19:08:43
【问题描述】:

我想在 Django 1.7 的表单中使用 typeahead.js。此外,我想使用基于类的视图来实现它。

据我了解问题,我需要创建一个视图,为来自 typeahead.js 的 ajax 请求生成 JSON 响应。

为此使用 django-braces 是个好主意吗?

到目前为止,我所拥有的是:

from braces.views import JSONResponseMixin

[...]

class TagList(JSONResponseMixin, ListView):
    """
    List Tags
    """
    model = Tag
    context_object_name = 'tags'

    def get(self, request, *args, **kwargs):
        objs = self.object_list()

        context_dict = {
            "name": <do something with "obs" to get just the name fields>
            "color": <do something with "obs" to get just the color fields>
        }

        return self.render_json_response(context_dict)

这就是我现在卡住的地方。我在正确的道路上吗?或者甚至可以(并且很容易)在没有第三方应用的情况下使用?

【问题讨论】:

    标签: python ajax json django typeahead.js


    【解决方案1】:

    我通常这样使用python json库:

    import json
    from django.http import HttpResponse
    
    class TagList(ListView):
        ...
        context_dict = {
                "name": <do something with "obs" to get just the name fields>
                "color": <do something with "obs" to get just the color fields>
        }
        return HttpResponse(json.dumps({'context_dict': context_dict}),
                        content_type='application/json; charset=utf8')
    

    但是在新的 Django 1.7 中你有 JsonResponse objects

    希望你觉得它有用。

    【讨论】:

    • 这应该被编辑。没有类应该返回一些东西。正确的应该是在 TagList 类中重新实现 get 方法。
    【解决方案2】:

    序列化非字典对象¶

    为了序列化 dict 以外的对象,您必须将 safe 参数设置为 False:

    response = JsonResponse([1, 2, 3], safe=False)
    

    https://docs.djangoproject.com/en/1.10/ref/request-response/#jsonresponse-objects

    编辑:

    但请注意,这会在您的代码 [1] 中引入潜在的严重 CSRF 漏洞,并且 Django 规范不建议这样做,因此它被称为不安全。如果您返回的内容需要身份验证并且您不希望第三方能够捕获它,那么不惜一切代价避免。

    为了缓解此漏洞,您应该将列表包装在字典中,如下所示: {'context': ['some', 'list', 'elements']}

    [1]https://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-07
      • 2021-02-23
      • 2021-10-28
      • 1970-01-01
      • 2017-02-24
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多