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

use*_*942 6 python django django-views

我认为标题很清楚.我想知道用户何时单击按钮在我的views.py中的函数中运行一段代码.让我说我有这个HTML:

<div>
    <input type="button" name="_mail" value="Enviar Mail">  
</div>
Run Code Online (Sandbox Code Playgroud)

如果用户点击它,我想运行此代码:

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

这就是我想做的一切.

编辑:这是我的观点:

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)
Run Code Online (Sandbox Code Playgroud)

And*_*kou 5

您应该在您的 中创建此函数views.py,将其映射到您的 urlurls.py并使用 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
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<div>
    <input type="button" id="buttonId" name="_mail" value="Enviar Mail">  
</div>
Run Code Online (Sandbox Code Playgroud)

Python:

def verFactura(request, id_factura):

    ...    

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

    ...
Run Code Online (Sandbox Code Playgroud)

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