In this part I continue my tutorial on Running Python Script by Clicking HTML Button. Here I will create a HTML form and submit button & once a user clicks on HTML button, values from HTML Form will be passed to a External Python Script and Output of script will be Mapped to HTML Page.
Before continuing this tutorial i will suggest you to watch the Part 1 of this tutorial where we Configured the Python Django Part for Creating HTML Template.



All the Code from this Video:

Python Django Code : 


Views.py : 




















from django.shortcuts import render
import
requests
import sys
from subprocess import run,PIPE
def button(request):
return render(request,home.html)
def output(request):
data=requests.get(https://www.google.com/)
print(data.text)
data=data.text
return render(request,home.html,{data:data})
def external(request):
inp= request.POST.get(param)
out= run([sys.executable,//mnt//e//work//djnago_testing//test.py,inp],shell=False,stdout=PIPE)
print(out)
return render(request,home.html,{data1:out.stdout})

Urls.py:












from django.conf.urls import url


from
django.contrib import admin

from . import views
urlpatterns = [
url(r^admin/, admin.site.urls),
url(r^$, views.button),
url(r^output, views.output,name=script),
url(r^external, views.external),
]

Home.html :

<!DOCTYPE html>
<html>
<head>
<title>
Python button script
</title>
</head>
<body>
<button onclick=location.href='{% url ‘script’ %}’>Execute Script</button> <hr>
{% if data %}
{{data | safe}}
{% endif %}
<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>

External Python Script :

import sys
import datetime
time=datetime.datetime.now()
output="Hi %s currentadfwffffdwadwd time is %s" % (sys.argv[1],time)
print(output)

Categorized in: