I sent an ajax get request to jquery But render_to_response does not work
I added below code
print("request is : ", self.request)
but empty is printed
please let me know how to fix or how to debugg
thank you~!
blog\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()
blog/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);
});
})
});
I suggest you try django braces. https://django-braces.readthedocs.io/en/latest/. It has built-in functions for ajax
I don't know anything about the model, so I just used your example as a reference. Then you can make a separate url for the PostDetailAjaxView. You can now call it via jquery using the GET as the method. If you want to use other methods you can use post_ajax(), put_ajax(), delete_ajax(), etc.