我向jquery发送了一个ajax get请求但是render_to_response不起作用我在下面添加了代码print("request is : ", self.request)
但是打印了空
请让我知道如何修复或如何调试
谢谢〜!
博客\ views_cbv.py
class PostDetailView(DetailView):
print("detail view")
model = Post
def render_to_response(self, context):
print("request is : ", self.request)
if self.request.is_ajax():
print("request is ajax ")
return JsonResponse({
'title': self.object.title,
'summary': truncatewords(self.object.content, 100),
})
return super().render_to_response(context)
post_detail = PostDetailView.as_view()
博客/ post_list.html
$(document).ready(function () {
$(document).on('click', '#post_list a', function (e) {
e.preventDefault();
const detail_url = $(this).attr("href");
<!-- alert(detail_url) -->
console.log("detail_url : ", detail_url )
$.get(detail_url)
.done((json_obj) => {
var $modal = $("#post-modal");
console.log("json_obj : ", json_obj)
$modal.find('.modal-title').html(json_obj.title);
$modal.find('.modal-body').html(json_obj.summary);
$modal.find('.btn-detail').attr('href', detail_url)
$modal.modal();
})
.fail((xhr, textStatus, error) => {
alert('failed : ', error);
});
})
});
我建议你试试django braces。 https://django-braces.readthedocs.io/en/latest/。它具有ajax的内置函数
from braces.views import AjaxResponseMixin
from braces.views import JsonRequestResponseMixin
class PostDetailAjaxView(AjaxResponseMixin, JsonRequestResponseMixin, View):
def get_ajax(self, request, *args, **kwargs):
post_pk = request.GET.get('pk', None)
post = Post.objects.get(pk=post_pk)
data = {
'title': post.title,
'summary': truncatewords(post.content, 100)
}
return self.render_json_response(data)
我对模型一无所知,所以我只是用你的例子作为参考。然后你可以为PostDetailAjaxView创建一个单独的url。您现在可以使用GET作为方法通过jquery调用它。如果要使用其他方法,可以使用post_ajax(),put_ajax(),delete_ajax()等。