我想在Django 1.7的表单中使用typeahead.js。此外,我想使用基于类的视图实现这一点。
据我所知,我需要创建一个视图,为来自typeahead.js的ajax请求生成一个JSON响应。
使用django大括号是个好主意吗?
到目前为止我得到的是:
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)
这就是我目前的困境。我走的路对吗?或者,如果没有第三方应用程序的话,这是否可能(而且很容易)?
序列化非字典对象
要序列化dict以外的对象,必须将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/
我通常使用python json库,如下所示:
但在新的Django 1.7中,您有JsonResponse objects
希望你觉得有用。
相关问题 更多 >
编程相关推荐