简体   繁体   English

单击一个按钮并从views.py中运行python function,在django中使用JS/ajax

[英]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.

相关问题 如何从模板文件夹中的ajax-html调用Django中views.py文件中的函数? - How make a call to a function in views.py file in Django from ajax-html in template folder? 如何在 Django 中单击 template.html 中的按钮时调用 views.py 中的函数 - How to call a function in views.py on clicking a button in template.html in django 在我的views.py,Django中使用ajax请求的结果 - Use the result of an ajax request in my views.py, Django 如何使用 AJAX 将查询集从 html 传递到 django 中的 views.py? - How to pass query sets from html to views.py in django using AJAX? Javascript到Django views.py? - Javascript to Django views.py? 如何将在我的html文件上单击的图像的URL传递给views.py中的python函数 - how to pass the url of image clicked on my html file to my python function in views.py Django Django框架:views.py中的Python函数无法找到json文件 - Django Framework: Python function in views.py unable to find the json file 我如何使用脚本在脚本文件或views.py中运行python函数来不加载页面 - How Can I run a python function in script file or in the views.py using javascript for not loading the page 从views.py访问pdf文件,该文件由Js在Django项目中创建 - Access a pdf file from views.py which is created by Js in a Django project Django:如何从views.py获取字典到javascript函数(html文件) - Django: how to get a dictionary from views.py into javascript function (html file)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM