Get the click event from a button in a django view

我是研究僧i 提交于 2019-12-03 07:48:39
Andrei 'finelord' Baibakou

You should create this function in your views.py, map it to the url in your urls.py and add event handler using JavaScript (pure JS or using jQuery as shown below):

JS (using 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.        

    ...

Note that if you're going to use POST method you should care about csrf (cross-site request forgery) protection as described HERE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!