从Django视图中的按钮获取click事件 [英] Get the click event from a button in a django view
问题描述
我认为标题很清楚。我想知道用户何时单击按钮以在我的views.py中的函数中运行一段代码。可以说我有这个html:
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='robot@server.com',
recipient_list=[request.user.email],
context=extra_context)
这就是我要做的。
编辑:这是我具有的视图:
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='imiguel@exisoft.com.ar',
recipient_list =['ignacio.miguel.a@gmail.com'],
context=extra_context)
return HttpResponseRedirect('../facturas')
return render(request,template, extra_context)
推荐答案
您应在 views.py
,将其映射到您的 urls.py
中的url,然后使用JavaScript(纯JS或 jQuery
如下所示):
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(使用 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
(跨站点请求伪造)如这里
Note that if you're going to use POST
method you should care about csrf
(cross-site request forgery) protection as described HERE
这篇关于从Django视图中的按钮获取click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!