从django视图中的按钮获取click事件
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:
我认为标题很清楚。我想知道用户何时单击按钮以在我的views.py中的函数中运行一段代码。让我说我有这个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)
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='imiguel@exisoft.com.ar',
recipient_list =['ignacio.miguel.a@gmail.com'],
context=extra_context)
return HttpResponseRedirect('../facturas')
return render(request,template, extra_context)
1 个解决方案
#1
4
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):
您应该在views.py中创建此函数,将其映射到urls.py中的url并使用JavaScript添加事件处理程序(纯JS或使用jQuery,如下所示):
JS (using jQuery
):
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.
...
Note that if you're going to use POST
method you should care about csrf
(cross-site request forgery) protection as described HERE
请注意,如果您要使用POST方法,则应关注csrf(跨站点请求伪造)保护,如此处所述
更多相关文章
- Python中int()函数的用法
- Python内置函数之匿名(lambda)函数
- python函数的属性
- python学习笔记10(函数一): 函数使用、调用、返回值
- 八大经典排序算法基本思想及代码实现(插入排序,希尔排序,选择排序,
- 贝叶斯学习 -- matlab、python代码分析(3)
- UNIX-LINUX编程实践教程->第八章->实例代码注解->写一个简单的sh
- Linux下objdump查看C程序编译后的汇编代码
- Linux下共享内存相关函数