'module'对象不可调用错误

时间:2013-09-14 23:28:12

标签: python ajax django django-views django-class-based-views

我有以下基于类的视图, 当我发出ajax请求时,我得到“模块”对象是不可调用的错误 /?id=145

有什么想法吗?

class CityList(ListView):
    template_name = "profile/profile.html"
    model = City

    def render_to_response(self, context, **response_kwargs):

        if self.request.is_ajax() and self.request.GET.get('query'):
            query = self.request.GET.get('query')
            city_filter = [{'name': i.name,
                                'id': i.id}
                                for i in City.objects.filter(
                                name__icontains=query)]
            results = city_filter
            return HttpResponse(json.dumps(results),
                                mimetype='application/json')
        elif self.request.GET.get('id'):
            query = self.request.GET.get('id')
            if query:
                return HttpResponse(json.dumps(list(self.object_list.filter(
                    id=query).values('name', 'id')
                )), mimetype='application/json')

1 个答案:

答案 0 :(得分:0)

data = serializers.serialize('json', self.object_list.filter(id=query))

彻底解决了我的问题。我不确定为什么json.dumps不起作用,但序列化器的工作方式与下面的代码相似。

  class CityList(ListView):
        template_name = "profile/profile.html"
        model = City

        def render_to_response(self, context, **response_kwargs):

            if self.request.is_ajax() and self.request.GET.get('query'):
                query = self.request.GET.get('query')
                city_filter = [{'name': i.name,
                                    'id': i.id}
                                    for i in City.objects.filter(
                                    name__icontains=query)]
                results = city_filter
                return HttpResponse(json.dumps(results),
                                    mimetype='application/json')
            if self.request.GET.get('id'):
                query = self.request.GET.get('id')
                if query:

                    data = serializers.serialize('json', self.object_list.filter(id=query))
                    return HttpResponse(data)