从Django形式调用函数而不渲染其视图 [英] call a function from django-form without rendering its view

查看:107
本文介绍了从Django形式调用函数而不渲染其视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django,我想创建一个网站

using Django I want to create a website on which


  1. 如果单击按钮,则会在服务器中调用一个函数。

我还希望满足以下条件:

And I also want a following condition:


  1. 单击按钮后,将不会重新渲染页面。

简单来说,我想在服务器中单击并运行python脚本。我已经如下创建了按钮和调用功能脚本,但是由于返回值是1而不是呈现功能,因此会导致错误。

In a simpler word, I want to button-click and the run python script in the server. I've created the button-and-call-function script as follows, but it causes error because returned value is 1 and not rendering function.

如何实现目标?

app_name / templates / app_name / index.html

app_name/templates/app_name/index.html

<body>
    <form action='some_function' method='GET'>
    <button type='submit'>Click Here</button>
    </form>
</body>






app_name / views.py


app_name/views.py

def some_function(request):
    print("do something here")
    return 1 # error is caused here but I don't want re-render






app_name / url .py


app_name/url.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.show_view, name='view'),
    path('do_something', views.do_something, name='do_something')
]

谢谢!

推荐答案

您可以使用AJAX异步运行python函数。如果要在单击按钮时运行python脚本,请使用 onclick事件侦听器调用AJAX函数。

You can use AJAX to run python functions asynchronously. If you want to run your python script when a button is clicked use the "onclick" event listener to call your AJAX function.

使用您在url中定义的URL。 py文件,然后视图将被异步调用。

Use the URL you defined in your urls.py file and the view will get called asynchronously.

您的HTML

<body>
   <input type='button' value='run function' onclick='runScript()'>
</body>

带有JQuery的Javascript将为我们提供一种简单的方法来进行AJAX调用

Javascript with JQuery will provide us with an easy way to make the AJAX call

function runScript() {
    $.ajax({
        url: 'do_something', //The URL you defined in urls.py
        success: function(data) {
          //If you wish you can do additional data manipulation here.
        }

    });
}

views.py

from django.http import HttpResponse

def some_function(request):
    #Code to run
    #More code to run
    return HttpResponse('Return data to ajax call')

如果我理解正确,则想运行

If I understood correctly you want to run python code when a button is clicked and the form's data is irrelevant.

如果要实际使用表单数据,则可能需要使用e.preventDefault()在您的Ajax调用中,以防止表单提交,然后通过AJAX函数发送数据。

If you are looking to actually use the form data then you may need to use e.preventDefault() in your ajax call to prevent the form from submitting and then send the data via your AJAX function.

这篇关于从Django形式调用函数而不渲染其视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆