render to response is not work for jquery ajax request

443 Views Asked by At

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);
            });

    })
});

github: https://github.com/hyunsokstar/ask_class

1

There are 1 best solutions below

2
On

I suggest you try django braces. https://django-braces.readthedocs.io/en/latest/. It has built-in functions for 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)

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.