'Move HTML variable through views to python script in Django

While working in Django I am trying to take a variable from HTML input, pass it to views.py for some decision making, then pass it from views.py to a separate python script in my project.

Here is my upload form in my HTML file, this step works fine:

            <form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}">
              {% csrf_token %}  
              <input type='file' name='document' accept='.csv' required><br>
              <label for='axis'>Which column is the x-axis?<label>
              <input type='number' name='axis' id='axis' required><br>
              <button type='submit' name='csvreader'>Bar Graph</button>
              <button type='submit' name='line_plot'>Line Graph</button>
              <button type='submit' name='scatter_plot'>Scatter Plot</button>
            </form>

Then in my views.py, I use it to check if the value is valid before calling the python script, also works fine:

def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST.get, request.FILES)
        file=request.FILES['document']
        df = pd.read_csv(file,header=None)
        data = pd.DataFrame(df)
        length = len(data.columns)
        item = Item()
        item.text = request.POST.get('axis', '')
        item.save()
        request.session['item.text'] = item.text
        if ((int(item.text) < 0)) | ((int(item.text) >= length)):
            HttpResponse("Your axis is not valid")
        if 'csvreader' in request.POST:
            csv = CSV.objects.create(doc=file)
            os.system('python csvreader2.py')
        if 'line_plot' in request.POST:
            csv = CSV.objects.create(doc=file)
            os.system('python line_plot.py')
        if 'scatter_plot' in request.POST:
            csv = CSV.objects.create(doc=file)
            os.system('python scatter_plot.py')
        return render(request, 'uploaded.html')

And finally, I want to use it to define which line of the csv file will be the x axis, this is my issue. I have no idea how to reference the variable in either the html page or views.py from here.

#Asks user which column they would like to use for x axis labels and takes it from the csv file
x_lab = 0
col_1= list(df[int(x_lab)])
col_1.pop(0)
done = 0
x_value = []
x_val = 0
count = 1

I'm not using Flask or Ajax for this project(assignment constraints), so I don't know how to reference this variable in my python script. I attempted reworking csvreader.py into a view of its own for easy movement, but then I kept getting error: 'main thread is not in main loop', so I assume I can't just have the python file become its own view.



Solution 1:[1]

If your python script takes an input and returns something, even if only a success indicator, make your code into a function and import it for your views:

In csvreader2.py

def create_graph(axis)
    ...#do work
    return True

Place your csvreader2.py in your django directory at the same level as views (or wherever else it makes sense for you)

In views.py

from .csvreader2 import create_graph

def upload(request):
   ...#do work
   success = create_graph(item.text)
   ...
   #pass  axis to your template as a context values
   if success:
       return render(request, 'uploaded.html', {"axis": item.text})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SamSparx