【问题标题】:Get the click event from a button in a django view从 django 视图中的按钮获取单击事件
【发布时间】:2014-09-11 08:36:57
【问题描述】:

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

【问题讨论】:

    标签: python django django-views


    【解决方案1】:

    您应该在您的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 所述

    【讨论】:

    • 我只是编辑问题。这就是我现在的观点,我只想在 if 语句中添加点击动作。你说使用 ajax 和 jquery 更容易吗?谢谢
    • 查看更新的答案。如果您想在不重新加载页面的情况下执行点击操作 - ajax 是不错的选择。但我更喜欢在views.py 中使用不同的功能来呈现页面并处理按钮单击等操作
    • 我的英语不太好,让我看看我是否明白。在 If 语句中,我应该输入此代码“if request.POST.get('click', False): (send email)”,并且我应该使用您在模板中建议的 js 代码?
    • 没错。但我建议一般的方法,您必须根据需要调整此代码。
    • 好的!我从来没有使用过ajax,所以最后一个问题:在“数据”字段中,“名称”可以为空吗?因为我在视图中使用 python 处理所有内容。谢谢
    猜你喜欢
    • 1970-01-01
    • 2016-02-13
    • 2023-04-02
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多