我正在使用 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 工作正常。任何想法???:(((
谢谢!!!!