2014-09-21 50 views
1

我想在我的Django 1.7中使用的形式使用typeahead.js。此外,我想用基于类的视图来实现它。JSON与Django的响应列表

据我了解这个问题,我需要创建一个视图,为来自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) 

这就是我坚持的时刻。我在正确的道路上吗?或者,如果没有第三方应用程序,甚至有可能(并且容易)去?

回答

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

希望你觉得它有用。

+0

这应该被编辑。没有班级应该回报什么。正确的应该是重新实现TagList类中的get方法。 – 2016-03-31 20:34:44