django 根据选择的值显示模板中的数据

gpfsuwkq  于 2023-04-13  发布在  Go
关注(0)|答案(2)|浏览(117)

嗨,朋友们,我需要帮助,因为我是django的新手!我需要根据从select中选择的选项显示我保存在表中的信息。当选择模板中的选择选项时,我使用JavaScript将值保存在变量中(我这样做没有问题)。我不能将该变量的值获取到get_context_data方法中,以便稍后在我的模板中显示它。JavaScript代码:

$(function () {  
    $('select[name="reporteFecha"]').on('change', function () {
        var fecha = $(this).val();
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: {
                'action': 'search_fecha',
                'fecha': fecha
            },
            dataType: 'json',
        })
    });
});

视图代码:

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
   
        ### I need to obtain within this function the value of the select in a variable ###
        CE = ConsumoElect.objects.filter(fecha = *value obtained from JavaScript*)
        
        context = {
            'CE': CE,

            'title': 'Reporte de Control de Electricidad',
            'entity': 'Reporte Electricidad',
            'list_url': reverse_lazy('cont_elect:Reporte_list'),
            'form': ReportForm(),
        }  
        return context

我需要在get_context_data中的一个变量中获取我用JavaScript捕获的值,以便以后能够在模板中显示它

xdnvmnnf

xdnvmnnf1#

get_context_data用于GET请求,而不是POST请求。它基本上不是用于计算或管理POST的呈现。要做到这一点,您必须重新定义post()方法。在您的情况下,您将有类似的内容:

class YourClass(view):
    def get_context_data(self, **kwargs):
        """
            It's useless to call the super get context data if you redefine it just after.
            Here you just create the "base" context (that you will have on GET and POST request).
        """
        context = super().get_context_data(**kwargs)
        context.update({
            'title': 'Reporte de Control de Electricidad',
            'entity': 'Reporte Electricidad',
            'list_url': reverse_lazy('cont_elect:Reporte_list'),
            'form': ReportForm(),
        }) # You update the super context_data to not override it
        return context

    def post(self, request, *args, **kwargs):
        """
            Here you redefine the behavior of the POST request
        """

        CE = ConsumoElect.objects.filter(fecha=request.POST.get('fecha')

        context = self.get_context_data() #retrieving the "base" context
        context['CE'] = CE
        return render(request, 'templatename.html', context)
        
    ```
aiqt4smr

aiqt4smr2#

看了一些视频教程,我发现一个帮助我解决问题的方法(虽然它没有使用JavaScript),该方法不是视图的类而是函数。

def Reporte3View(req):
    fecha = req.POST.get('fecha')
    ConsE = list(TipoPGD.objects.all().values('id', 'name'))
    lista_CE=[]
    
    if fecha == None:
        for item in ConsE:
            B = ConsumoElect.objects.filter(pgd=item['id'])
            lista_CE.append(B)
    else:
        for item in ConsE:
            B = ConsumoElect.objects.filter(pgd=item['id'], fecha=fecha)
            lista_CE.append(B)

    context = {
        'lista_CE': lista_CE,
        'entity': 'Reporte Electricidad',
        'title': 'Reporte de Control de Electricidad',
        'list_url': reverse_lazy('cont_elect:Reporte3'),
        'form': Report3Form(),
        #'form': Report3Form(initial={'fecha': '2023-04-01'}), # Me muestra este valor
    }
    form = Report3Form()
    return render(req, 'Reporte/reporte_elect3.html', context )

相关问题