Get the click event from a button in a django view

前端 未结 1 946
抹茶落季
抹茶落季 2021-02-06 09:13

i think the title is pretty clear. I want to know when the user clicks the button to run a piece of code in a function in my views.py. lets say i have this html:



        
相关标签:
1条回答
  • 2021-02-06 09:39

    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

    0 讨论(0)
提交回复
热议问题