0

I'm trying to learn how to transfer my Highchart from a python script on to Django. I've been using this solution thread to get there (but in vain so far).

I've got a python script called script.py that returns an object named chart_data. Now in Django, I'd like a function in my views.py to execute that script.py file, grab the chart_data object and allocate it to a new object called 'data'.

My script.py file is stored in a directory called /scripts/ in my project root directory, and it contains its own __init__.py file.

With the code below the server returns an error that states: global name 'chart_data' is not defined.

Any explanations as to what I'm doing wrong here would be greatly appreciated.

### views.py

from __future__ import unicode_literals
import datetime
import subprocess
import scripts

def plot(request, chartID = 'chart_ID', chart_type = 'line', chart_height = 500):

    raw = subprocess.Popen('~/scripts/script.py', shell=True)

    data = chart_data

    chart = {"renderTo": chartID, "type": chart_type, "height": chart_height,}
    title = {"text": 'my title here'}
    xAxis = {"title": {"text": 'xAxis name here'}, "categories": data['Freq_MHz']}
    yAxis = {"title": {"text": 'yAxis name here'}}
    series = [
    {"name": 'series name here', "data": data['series name here']},
    ]

    return render(request, '/chart.html', {'chartID': chartID, 'chart': chart,
                                                'series': series, 'title': title,
                                                'xAxis': xAxis, 'yAxis': yAxis})
Joss
  • 197
  • 1
  • 5
  • 18

2 Answers2

1

Yes, chart_data is not defined anywhere in this code.

You seem to be running your script as an external process, and then expecting that Django will somehow know about the variables it defines. That's not how it works at all.

Rather than calling your script via Popen, you should import it like the other Python modules you use. Then you can call any of its functions and assign their return values to whatever you like.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Put your script inside the Django app you are using and then import it:

from my_app.chart_data import chart_data
Alex
  • 1,252
  • 7
  • 21