如何使用Django在HTML按钮上执行file.py? [英] How to execute file.py on HTML button press using Django?

查看:377
本文介绍了如何使用Django在HTML按钮上执行file.py?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是单击Django网页上的HTML按钮,这将执行本地python脚本。

My goal is to click an HTML button on my Django web page and this will execute a local python script.

我正在创建本地Web应用程序作为界面到一个项目。它不会被托管,并且将始终只在我的本地计算机上运行。我的项目使用python脚本运行(该脚本执行了针对我的项目的许多测试)。我只需要在Web界面中单击一个按钮即可在计算机上执行此脚本。

I am creating a local web application as an interface to a project. This will not be hosted and will always just run on my local machine. My project is run with a python script (which carries out numerous tests specific to my project). All I need is for a button in my web interface to execute this script on my machine.

我有一个用于整个网页的模板index.html。我想我可能需要在按下按钮时调用某种形式的views函数?

I have a template index.html where the whole web page is located. I presume I need to call some form of views function possibly when the button is pressed?

How to execute python code by django html button?

此问题建议:

def index(request):
    if request.method == 'GET':
        return render(request, 'yourapp/index.html', {'output': ''})
    elif request.method == 'POST':
        py_obj = mycode.test_code(10)
        return render(request, 'yourapp/output.html', {'output': py_obj.a})

我只是作为测试尝试了此操作,但是转到URL(位于适当的views.py中)时没有任何反应:

I tried this just as a test but nothing happened when I went to the URL (located in the appropriate views.py):

def runtest(request):
    print("Hello World")
    Popen(['gnome-terminal', '-e', 'echo "Hello World"'], stdout=PIPE)
    return

但是我不放弃为了了解这是否达到了我的要求,我正在努力理解答案的含义。

However I don't quite understand if this achieves what I need it to, I am struggling to understand what the answer is suggesting.

在Django框架中的哪里可以指定对本地的调用

Where in the Django framework can I specify a call to a local python script when a button is pressed?

(我对Web应用程序的经验非常有限,这只是一个带有一些按钮的简单界面,用于运行测试)

(I have very limited experience with web applications, this is simply just meant to be a simple interface with some buttons to run tests)

推荐答案

您要尝试执行的操作是单击按钮时提交表单。然后,您可以从脚本中导入要运行的函数,然后在视图中调用它们。然后,您将重定向到同一页面。

what you're going to want to try and do is submit a form on the button click. You can then import the functions you want to run from the script and call them in your view. You then redirect to the same page.

我希望这会有所帮助!

index.html

<form method="post">
    {% csrf_token %}
    <button type="submit" name="run_script">Run script</button>
</form>

views.py

if request.method == 'POST' and 'run_script' in request.POST:

    # import function to run
    from path_to_script import function_to_run

    # call function
    function_to_run() 

    # return user to required page
    return HttpResponseRedirect(reverse(app_name:view_name)

这篇关于如何使用Django在HTML按钮上执行file.py?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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