gpt4 book ai didi

python - 如何从 Django 中的表单调用 Python 函数?

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:41 25 4
gpt4 key购买 nike

我正在尝试从我的模板之一中的表单调用函数来计算 Django 项目中的值。该函数是Python 中的。我就是这样做的。我将 myScript.py 保存在 views.py 所在的应用程序文件夹中。

template.html:

...
<button type="submit" class="btn btn-primary" value="nonlBis" name="bisBtn">Submit</button>
...

views.py:

from app.myScript import *
...
def Functions(request):
if(request.GET.get('nonlBis')):
print(myScript.myFunction())

最佳答案

我会这样做。

  1. 为您的按钮提供一个“ID”。
<button type="submit" class="btn btn-primary" value="nonlBis" name="bisBtn" id="btnSoSpecial">Submit</button>
  • 将 Js 函数绑定(bind)到该按钮。将【YOUR API URL HERE】替换为您在 urls.py 中创建的真实 URL。
  • $("#btnSoSpecial").bind('click', function () {
    $.ajax({
    type: "POST",
    url: "【YOUR API URL HERE】", //replace it with your real url
    data: {
    csrfmiddlewaretoken: '{{csrf_token}}',
    nonlBis:$(this).data('value'),// This part might needs some modify
    },
    async: true,
    success: function (ret) {
    //Do stuffs with returning data
    },
    error: function (xhr) {
    console.log('Something went wrong.Deal with it.');
    console.log(xhr);
    }
    })
    });
  • 将 API url 链接到views.py 中的函数,也许就像
  • path('api/functionA', views.Functions, name='functionA'),

    关于python - 如何从 Django 中的表单调用 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56051285/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com