spe*_*ndo 1 python django ajax json typeahead.js
我想在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)
Run Code Online (Sandbox Code Playgroud)
那是我目前停留的地方。我在正确的道路上吗?还是有可能(且容易)没有第三方应用程序?
序列化非字典对象
为了序列化除dict以外的对象,必须将safe参数设置为False:
response = JsonResponse([1, 2, 3], safe=False)
Run Code Online (Sandbox Code Playgroud)
https://docs.djangoproject.com/zh/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 库,如下所示:
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')
Run Code Online (Sandbox Code Playgroud)
但在新的 Django 1.7 中你有JsonResponse 对象
希望你觉得它有用。
| 归档时间: |
|
| 查看次数: |
11534 次 |
| 最近记录: |