3

我正在使用 Django 和 AJAX。基本上,我只是希望 javascript (vote.js) 将一些数据发布到 Django 视图,然后视图以 JSON 数据响应 html,以便我的 javascript 的回调函数可以使用来自服务器的响应.

所以这是我的代码:

投票.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;
});

视图.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 工作正常。任何想法???:(((

谢谢!!!!

4

2 回答 2

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)

于 2013-08-11T16:43:16.210 回答
0

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

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

于 2013-08-11T16:33:17.767 回答