在Django视图中获取按钮的点击事件

8 投票
1 回答
24561 浏览
提问于 2025-04-18 14:03

我觉得标题已经很清楚了。我想知道当用户点击按钮时,如何在我的 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 个回答

6

你需要在你的 views.py 文件里创建这个函数,然后在 urls.py 文件中把它和网址对应起来,接着用JavaScript(可以是纯JavaScript或者使用 jQuery,下面会有示例)来添加事件处理器:

JavaScript(使用 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(跨站请求伪造)保护,具体内容可以在 这里找到。

撰写回答