从 django-form 调用函数而不渲染其视图

永川圭*_*川圭介 0 django django-forms

使用 Django 我想创建一个网站

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

而且我还想要以下条件:

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

简而言之,我想单击按钮并在服务器中运行 python 脚本。我已经按如下方式创建了按钮和调用函数脚本,但它会导致错误,因为返回值为 1 而不是渲染函数。

我怎样才能实现目标?


app_name/templates/app_name/index.html

<body>
    <form action='some_function' method='GET'>
    <button type='submit'>Click Here</button>
    </form>
</body>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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')
]
Run Code Online (Sandbox Code Playgroud)

谢谢!

dan*_*bee 5

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.

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

Your HTML

<body>
   <input type='button' value='run function' onclick='runScript()'>
</body>
Run Code Online (Sandbox Code Playgroud)

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.
        }

    });
}
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

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

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.