How to execute file.py on HTML button press using Django?

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)

Asked By: HCF3301

||

Answers:

You want to try to 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))
Answered By: James

Adding to answer above. You can run the function in a different view completely:

<form method="post" action="{% url 'app:view/function' %}">
{% csrf_token %}
<button class="btn btn-danger btn-block btn-round">Perform task</button>
</form>

And render whatever template you want (same template will execute task but seem like nothing has happened). This is handy if you already have a ‘POST’ form handler.

Answered By: Josh
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.