我认为标题很清楚。我想知道用户何时单击按钮在我的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)
答案 0 :(得分:4)
您应该在views.py
中创建此功能,将其映射到urls.py
中的网址,并使用JavaScript(纯JS或使用jQuery
添加事件处理程序,如下所示):< / p>
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
方法,则应该关注HERE
csrf
(跨网站请求伪造)保护