Answer a question

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

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.

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?

This question suggests:

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

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.

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

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

Answers

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.

I hope this helps!

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)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐