from django.http import HttpResponse from django.http import JsonResponse from django.views.generic import ListView, DetailView from django.views.generic import TemplateView from .models import Specialization class SpecListView(ListView): model = Specialization template_name = 'specializations/specialization.html' def get_context_data(self, **kwargs): context = super(SpecListView, self).get_context_data(**kwargs) root = Specialization.objects.get(pk=1) context['root'] = root context['children'] = root.get_children() context['roots'] = Specialization.objects.root_nodes() # context['roots'] = Specialization.objects.filter(name='_root') # Migrate with this enabled return context def test_page(request): if request.method == 'POST': if request.is_ajax(): spec_id = request.POST.get('spec_id') spec = Specialization.objects.get(pk=spec_id) children = spec.get_children() return JsonResponse({"hello": 'yes'}) else: return JsonResponse({"hello": "python"}) import json def test_spec(request): spec = Specialization.objects.get(pk=2) children = spec.get_children() return HttpResponse(json.dumps(children)) class SpecChildrenDetailView(DetailView): model = Specialization def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class JSONResponseMixin(object): def render_to_json_response(self, context, **response_kwargs): return JsonResponse( self.get_data(context), **response_kwargs ) def get_data(self, context): return context class JSONView(JSONResponseMixin, TemplateView): def render_to_response(self, context, **response_kwargs): context = {'test': 'data'} return self.render_to_json_response(context, **response_kwargs)