Перенаправление маршрута из ajax с использованием подклассов представления на основе классов в Django


I'm curios and just got started learning about class based views in Django and I'm testing it with AJAX.
The idea is to get the data from the object (1/get-report) and redirect from AJAX to url which will be rendered from subclass (show_report route below).
This is what I have:

  • urls.py
    path("<int:pk>/get-report", ShowReportForDevice.as_view(), name="daily-report"),
    path("show-report/", ShowGraphReport.as_view(), name="show-report"),
  • views.py
# Parent class
class ShowReportForDevice(DetailView):
    model= ModbusDevice #queryset = ModbusDevice.objects.all()
    template_name= None
    checked_vars=[]
    dev_id=-1


    def get(self, request, *args, **kwargs):
        if request.is_ajax():
             # Data from client I want to be visible in the child class (methods)
            self.checked_vars= request.GET.getlist('myvars[]')  #myvars= kwargs.get('myvars[]') # None
            self.dev_id= request.GET.get('dev_id')
            # response created:
            data={}
            data['redirect']='/show-report'
            data['success']=True
            return JsonResponse(data, status=200)

# Child class
class ShowGraphReport(ShowReportForDevice):
    template_name= 'modbus_app/report2.html'
    data={}

    # Q1: Do I need to overrided this method if I only need parent class attributes? 
    # Q2: Is "context" variable parent attribute ? This function doesn't get called, but "get" is called
    def get_context_data(self, **kwargs):
        context = super(ShowGraphReport, self).get_context_data(**kwargs)
        context.update({
            'foodata': 'bardata',
        })
        print(self.dev_id)
        print(self.checked_vars)
        return context

#  I must override in order to render template
    def get(self, request, *args, **kwargs):
        # Q3: How to get the "context" variable here?
        print(self.dev_id) # not updated  still -1
        print(self.data) # not updated still {}
        return render(request, self.template_name, self.data)


  • javascript
    function reportBtn(id) {
        var checked_variables = getSelectedCheckboxValues('variables')
        $.ajax({
            type: 'GET',
            crossDomain: false,
            dataType: 'json',
            cache: false,
            url: id + '/get-report',
            data: {"dev_id": id, 'myvars': checked_variables},
            success: function (response) {
                console.log('Report done', response);
                window.location.href = response.redirect; // this will be '/show-report'
            },
            error: function (response) {
                console.log('Report error');
            }
        })
    }

Некоторые вопросы (Q1, Q2, Q3) в коде ставят меня в тупик.
Я предполагаю, что есть решение с использованием лучшей архитектуры, но я хотел бы знать, как решить проблему с помощью этого подхода. Спасибо

Вернуться на верх