Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display the console output to HTML in Django?

So I'm using Django framework to display the console output to the HTML. To execute the command, I'm using the check_output of subprocess module in Python. Which receives the input from the HTML input form. The problem is that I only see "None" on the HTML page, which is the default value of output in views file. Below is the code of the views file and HTML file. I'm a novice in this so I'd appreciate your assistance.

Views.py

from django.shortcuts import render
from django.shortcuts import redirect
from .forms import command_form
import subprocess as sp


# Create your views here.

def welcome_page(request):
    output=""
    if request.method == "POST":
        myform = command_form(request.POST)
        if (myform.is_valid()):
            execute_command = myform.cleaned_data['cmd_string']
            output = sp.check_output(execute_command, shell=True)
        else:
            myform = command_form()
        return render(request, 'ovs/welcome.html', {'output': output})
    else:
        return render(request, 'ovs/welcome.html', {})

welcome.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>welcome to ovs GUI</title>
</head>
<body>
    <h3>Choose the option:</h3>
    <form method="POST">{% csrf_token %}
        Enter the command: <input type="text" name="cmd_string" id="cmd_string"/>
        <input type="submit" value="Run"/>
    </form>
    <h3>{{ output }}</h3>
</body>
</html>

forms

from django import forms


class command_form(forms.Form):
    command = forms.CharField(max_length=200)
like image 960
आनंद Avatar asked Mar 24 '17 06:03

आनंद


3 Answers

You are not rendering the form field correctly to your HTML. You have created a command_form form and you never exploit it. However, you should use camel case name for python classes, like this CommandForm.

Inside your HTML, write this:

<form method="POST">{% csrf_token %}
    Enter the command: {{ myform }}
    <input type="submit" name="submit_cmd" value="Run" />
</form>
{% if output %}<h3>{{ output }}</h3>{% endif %}
{% if exit_code %}<h3>Your command returned an error: {{ error_msg }}</h3>{% endif %}

{{ my_form }} will expand, automatically, to <input type="text" ...>

Now, write your welcome_page view like this:

def welcome_page(request):
    output = ""
    # Initialize the form. At this point you have an unbound/invalid form
    myform = command_form()  # better write it as CommandForm

    if request.method == "POST":
        myform = command_form(request.POST)
        if myform.is_valid():
            # execute_command variable, should now contain the command typed by the user in the text box
            execute_command = myform.cleaned_data['command']
            try:
                # If the return code is non-zero, CalledProcessError will be raised
                output = sp.check_output(execute_command, shell=True)
            except sp.CalledProcessError:
                exit_code, error_msg = output.returncode, output.output
        else:
            # Do something when the form is not valid. Maybe add a message or something, or not implement else clause at all.
    return render(request, 'ovs/welcome.html', locals())

Warning! As per the docs say:

Using shell=True can be a security hazard.

like image 152
nik_m Avatar answered Oct 21 '22 20:10

nik_m


You can use REST framework to return a Response so you don't have to worry about handling it in HTML. Just install the rest_framework and do this:

from rest_framework.response import Response

return Response(data)
like image 35
Ajay Kumar Avatar answered Oct 21 '22 20:10

Ajay Kumar


views.py

from django.shortcuts import render
from django.shortcuts import redirect
from test.forms import CommadForm
import subprocess as sp

def welcome_page(request):
    if request.method == "POST":
        myform = CommadForm(request.POST)
        if myform.is_valid():
            execute_command = myform.cleaned_data['command']
            try:
                output = sp.check_output(execute_command, shell=True)
            except sp.CalledProcessError:
                output = 'No such command'
        else:
            myform = CommadForm()
        return render(request, 'ovs/welcome.html', {'output': output})
    else:
        return render(request, 'ovs/welcome.html')

forms.py

class CommadForm(forms.Form):
    command = forms.CharField(max_length=200)
like image 25
Vivek Sahu Avatar answered Oct 21 '22 18:10

Vivek Sahu