从django视图中的按钮获取click事件

时间:2014-07-20 21:08:13

标签: python django django-views

我认为标题很清楚。我想知道用户何时单击按钮在我的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)

1 个答案:

答案 0 :(得分:4)

您应该在views.py中创建此功能,将其映射到urls.py中的网址,并使用JavaScript(纯JS或使用jQuery添加事件处理程序,如下所示):< / p>

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方法,则应该关注HERE

所述的csrf(跨网站请求伪造)保护