I am writing a webpage that can run a python script by clicking a button on html. Here is what I have: views.py
from django.shortcuts import render
import requests
import sys
from subprocess import run,PIPE
def external(request):
inp= request.POST.get('param')
out= run([sys.executable,'test.py',inp],shell=False,stdout=PIPE)
print(out)
return render(request,'home.html',{'data1':out.stdout})
urls.py
from django.urls import path
from . import views
# urlconf
urlpatterns = [
path('external/', views.external)
]
home.html
<html>
<head>
<title>
Python button script
</title>
</head>
<body>
<form action="/external/" method="post">
{% csrf_token %}
Input Text:
<input type="text" name="param" required><br><br>
{{data_external}}<br><br>
{{data1}}
<br><br>
<input type="submit" value="Execute External Python Script">
</form>
</body>
</html>
The problem is with this line of code: out= run([sys.executable,'test.py',inp],shell=False,stdout=PIPE)
from views.py. How can I fix this? Thanks!
CodePudding user response:
You are probably using this view(external) for both the POST
method and the GET
method, and you do not have data in the get method, so you get an error.
try this:
def external(request):
if request.method == "POST":
inp= request.POST.get('param')
out= run([sys.executable,'test.py',inp],shell=False,stdout=PIPE)
print(out)
return render(request,'home.html',{'data1':out.stdout})
else:
return render(request,'home.html')