[英]Click a button and run a python function from views.py with JS/ajax in django
I've been reading this days about how can I call a python function
when I press a button and I'm very confused.这几天我一直在阅读有关当我按下按钮时如何调用python function
并且我很困惑的信息。 One of the things that I saw is that I have to use ajax
and most of the people use jquery
to do it.我看到的一件事是我必须使用ajax
而大多数人使用jquery
来做到这一点。
If I understood correctly the structure has to be similar to this,如果我理解正确,结构必须与此类似,
$(document).ready(function() {
$.ajax({
url: '',
type: '',
data: {'A':0},
dataType:'',
success: function(resp){
console.log(resp);
}
});
});
With this information, my final code is,有了这些信息,我的最终代码是,
views.py视图.py
def vista_sumar(request):
if request.method == 'POST':
a = request.POST['a']
b = request.POST['b']
c = int(a) + int(b)
ctx = {'Result':c}
return render(request,'main.html',ctx)
urls.py网址.py
from project.views import vista_sumar
urlpatterns = [
path('prueba/',vista_sumar),
]
main.html main.html
<input type="button" value="PRUEBA" class="boton">
<script src="{% static '/js/jquery-3.4.1.min.js' %}"></script>
<script type="text/javascript" src="{% static '/js/filters.js' %}"></script>
filters.js (the big fail) filters.js (大失败)
$('#prueba').click(function() {
alert('boton is working')
a =1;
b =3;
$.ajax({
method: 'POST',
url: '/../../prueba/',
data: {
'a': a,
'b': b,
},
dataType: "json",
success: function(response) {
alert(response.Result);
}
});
});
I know the button is working because the first alert
is working.我知道该按钮正在工作,因为第一个alert
正在工作。 The problem is when I use ajax
.问题是当我使用ajax
时。
The code error is 403=Forbbiden and is failing in the ajax.send()
代码错误是 403=Forbbiden 并且在ajax.send()
中失败
Can somebody help me?有人可以帮助我吗?
EDIT With the help of @epikstar I solved one thing, I forgot the CSRF
.编辑在@epikstar 的帮助下,我解决了一件事,我忘记了CSRF
。 I added in my js file
,我在我的js file
中添加了,
$('#prueba').click(function() {
alert('boton pulsado');
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
alert(csrftoken)
a =1;
b =3;
$.ajax({
url: '/../../prueba/',
type: 'POST',
headers:{"X-CSRFToken": csrftoken},
data: {
'a': a,
'b': b,
},
dataType: "json",
cache: true,
success: function(response) {
alert('succes')
alert(response.Result);
}
});
alert('fin')
});
I imported in my views.py
我在views.py
中导入
from django.template.context_processors import csrf
And I add this line in my main.html
我在我的main.html
中添加了这一行
<input type="button" value="PRUEBA" id="prueba">{% csrf_token %}
But it is still not working.但它仍然无法正常工作。 BUT the problem is different because I added too a print
in my python function
and it shows the result 4, therefore the problem nos is that I'm not returning correctly the result.但是问题有所不同,因为我在python function
中添加了一个print
并且它显示了结果 4,因此问题是我没有正确返回结果。
def vista_sumar(request):
if request.method == 'POST':
a = request.POST['a']
b = request.POST['b']
c = int(a) + int(b)
ctx = {'Result':c}
print(ctx)
return render(request,'main.html',ctx)
It prints 4
它打印4
But i added a console.log(response);
但我添加了一个console.log(response);
and console.log(response.Result);
和console.log(response.Result);
inside the success
and don't return anything...里面的success
,不返回任何东西......
Thank you very much.非常感谢。
You should add the CSRF token like this:您应该像这样添加 CSRF 令牌:
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
//example ajax
$.ajax({
url: url,
type: 'POST',
headers:{
"X-CSRFToken": csrftoken
},
data: data,
cache: true,
});
or you can add it directly from django variable:或者您可以直接从 django 变量中添加它:
$.ajax({
type: 'POST',
headers:{
"X-CSRFToken": '{{ csrf_token }}'
}
})
take a look here to discover what csrf token does: https://docs.djangoproject.com/fr/2.2/ref/csrf/看看这里以发现 csrf 令牌的作用: https://docs.djangoproject.com/fr/2.2/ref/csrf/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.