使用Django的JSONResponseMixin来响应AJAX请求

时间:2013-08-11 13:53:18

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

我正在使用Django& AJAX。基本上,我只是想让javascript(vote.js)发布一些数据 到Django View,反过来,View用JSON数据回复到html,这样我的javascript回调函数就可以使用来自服务器的响应了。

所以这是我的代码:

vote.js

$(document).on('click', 'a.upvote', function() {
    .....

    var xhr = {
        'id': id,
        'upvote': upvote,
    };

    $.post(location.href, xhr, function(data) {
        question.find('.rating').html(data.rating)
    });

    return false;
});

views.py

//I copied this JSONResponseMixin directly from official Django doc
class JSONResponseMixin(object):
    def render_to_response(self, context):
        "Returns a JSON response containing 'context' as payload"
        return self.get_json_response(self.convert_context_to_json(context))

    def get_json_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        return http.HttpResponse(content,
                                 content_type='application/json',
                                 **httpresponse_kwargs)

    def convert_context_to_json(self, context):
        "Convert the context dictionary into a JSON object"
        # Note: This is *EXTREMELY* naive; in reality, you'll need
        # to do much more complex handling to ensure that arbitrary
        # objects -- such as Django model instances or querysets
        # -- can be serialized as JSON.
        return json.dumps(context)


class MyListView(JSONResponseMixin, TemplateResponseMixin, DetailView):
    def post(self, request, *args, **kwargs):
        id = request.POST.get('id')
        .....

        data = {'rating': question.rating}

        return render_to_response(data)


    def render_to_response(self, context):
        if self.request.is_ajax():
            return JSONResponseMixin.render_to_response(self, context)
        else:
            return TemplateResponseMixin.render_to_response(self, context)

然而,这样做并点击我的"投票"触发javascript POST的html按钮给我一个TemplateDoesNotExist错误:

错误

.....
File "/Library/Python/2.7/site-packages/django/template/loader.py", line 139, in find_template                                                      
    raise TemplateDoesNotExist(name)                                               
TemplateDoesNotExist: {'rating': 1}

看起来我的最后5行views.py工作正常。 任何的想法??? :(((

感谢!!!!

2 个答案:

答案 0 :(得分:2)

class MyListView(JSONResponseMixin, TemplateResponseMixin, DetailView):
    def post(self, request, *args, **kwargs):
        id = request.POST.get('id')
        .....

        data = {'rating': question.rating}

        return render_to_response(data)

你最终在这里调用错误的render_to_response方法,即django.shortcuts中的快捷功能,我猜你已经在你的views.py中导入了。

请改用return self.render_to_response(data)

答案 1 :(得分:0)

https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render-to-response

render_to_response需要模板名称作为第一个参数。