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:
<div>
<input type="button" name="_mail" value="Enviar Mail">
</div>
and i want to run this code if the user clicks on it:
send_templated_mail(template_name='receipt',
from_email='[email protected]',
recipient_list=[request.user.email],
context=extra_context)
that´s all i want to do.
EDIT: this is the view that i have:
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='[email protected]',
recipient_list =['[email protected]'],
context=extra_context)
return HttpResponseRedirect('../facturas')
return render(request,template, extra_context)
To call a view function from template with Python Django, we can add a link to the URL of the view function. to add a link to the view with name delete_product in admin_page. html. to add the path to the delete_product view.
add the href to the button class and add a line in urls.py. once the button is clicked it will call the view it import's the function and it will call that function.
It is a javascript library designed to allow us to write less or no javascript at all. It acts as a way to send AJAX requests without you writing any javascript. It uses native browser features directly from HTML. So, we can use HTMX to create interactive templates in our Django application.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With