Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  75] [ 2]  / answers: 1 / hits: 19453  / 5 Years ago, wed, january 30, 2019, 12:00:00

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)


More From » python

 Answers
13

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

[#52688] Thursday, January 24, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sam

Total Points: 711
Total Questions: 96
Total Answers: 107

Location: Burkina Faso
Member since Thu, Dec 23, 2021
2 Years ago
;