Dimitris Kougioumtzis Blog About technology

Ajax Mixin for ListView and DetailView

Category Django

Posted on Sept. 25, 2018



Ajax Mixin for ListView and DetailView


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class AjaxMixin:
    '''
    Example:

    class ListView(AjaxMixin, ListView):
        ajax_template = 'partials/results.html'

    class DetailView(AjaxMixin, DetailView):
        ajax_template = 'partials/results.html'
    '''
    def get(self, request, *args, **kwargs):
        if(hasattr(self, 'get_object')):
            self.object = self.get_object()
        else:
            self.object_list = self.get_queryset()

        context = self.get_context_data()
        if self.request.is_ajax():
            ajax_template = self.ajax_template
            result = render_to_string(
                ajax_template, context, request=request
            )
            return JsonResponse({'result': result})
        else:
            return self.render_to_response(context)

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere