从Django vi中的按钮获取click事件

2024-06-20 15:05:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得标题很清楚。我想知道用户何时单击按钮在my views.py中的函数中运行一段代码。假设我有这个html:

<div>
    <input type="button" name="_mail" value="Enviar Mail">  
</div>

如果用户单击此代码,我将运行此代码:

send_templated_mail(template_name='receipt',
                    from_email='robot@server.com',
                    recipient_list=[request.user.email],
                    context=extra_context)

我只想这么做。

编辑:这是我的视图:

def verFactura(request, id_factura):
    fact = Factura.objects.get(pk = id_factura)
    cliente = Cliente.objects.get(factura = fact)
    template = 'verfacturas.html'
    iva = fact.importe_sin_iva * 0.21
    total = fact.importe_sin_iva + iva

    extra_context = dict()
    extra_context['fact'] = fact
    extra_context['cliente'] = cliente
    extra_context['iva'] = iva
    extra_context['total'] = total


    if  (here i want to catch the click event):
        send_templated_mail(template_name='receipt',
                    from_email='imiguel@exisoft.com.ar',
                    recipient_list =['ignacio.miguel.a@gmail.com'],
                    context=extra_context)

        return HttpResponseRedirect('../facturas')



return render(request,template, extra_context)

Tags: 代码用户namecomemailrequestcontextmail
1条回答
网友
1楼 · 发布于 2024-06-20 15:05:51

您应该在views.py中创建此函数,将其映射到urls.py中的url,并使用JavaScript(纯JS或使用jQuery)添加事件处理程序,如下所示:

JS(使用jQuery):

$('#buttonId').click(function() {    
    $.ajax({
        url: your_url,
        method: 'POST', // or another (GET), whatever you need
        data: {
            name: value, // data you need to pass to your function
            click: true
        }
        success: function (data) {        
            // success callback
            // you can process data returned by function from views.py
        }
    });
});

HTML格式:

<div>
    <input type="button" id="buttonId" name="_mail" value="Enviar Mail">  
</div>

Python:

def verFactura(request, id_factura):

    ...    

    if request.POST.get('click', False): # check if called by click
        # send mail etc.        

    ...

注意,如果您要使用POST方法,您应该关心csrf(跨站点请求伪造)保护,如HERE所述

相关问题 更多 >