skip to Main Content

Sure, here’s a Markdown version of your question for Stack Overflow:


Issue with Passing Data from Django Views to JavaScript in Template

I’m trying to pass data from my Django view to JavaScript in my template, but I’m encountering an issue where the parameters I’m passing appear to be empty when I inspect the webpage.

Views.py

def homepage(request):
    selected_model = request.GET.get('model', '')

    if selected_model == '1':
        df = pd.read_csv(os.path.join(settings.BASE_DIR, 'files', 'data', 'preprocessed_price_optimization_dataset.csv'))
        model_path = os.path.join(settings.BASE_DIR, 'files', 'data', 'price_optimization_model.h5')

        X = df[['product_id', 'category_id', 'brand_encoded', 'historical_price_scaled']] 
        y = df['historical_price'] 
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

        loaded_model = load_model(model_path)

        predictions = loaded_model.predict(X_test)
        evaluation = loaded_model.evaluate(X_test, y_test)

        actual_data = [1, 2, 3, 4, 5]
        predicted_data = [6, 7, 8, 9, 10]

        context = {
            'actual_data': actual_data,
            'predicted_data': predicted_data,
        }
    else:
        print("no actual and predicted data")
        context = {}

    return render(request, 'base.html', context)

base.html

<select id="visualSelector" name="model" onchange="printSelectedValue({{ actual_data|safe }}, {{ predicted_data|safe }})">
    <option value="0">---</option>
    <option value="1">SCATTERPLOT</option>
    <option value="2">LINEPLOT</option>
</select>

JavaScript

function printSelectedValue(actualData, predictedData) {
    var selectedValue = document.getElementById('visualSelector').value;
    var selectedModelValue = document.getElementById('modelSelector').value;

    if (selectedModelValue === '0') {
        console.log("No model selected");
        return; 
    }

    var canvas = document.getElementById('plotCanvas');

    if (selectedValue === '0') {
        canvas.style.backgroundColor = 'red';
        console.log("value 0:", actualData);
    } else if (selectedValue === '1') {
        canvas.style.backgroundColor = 'blue';
        console.log("value 1:", predictedData);
    } else if (selectedValue === '2') {
        canvas.style.backgroundColor = 'green';
        console.log("value 2:");
    }
}

Issue

When inspecting the webpage, the parameters actualData and predictedData appear to be empty. I’ve tried using {{ variablename | safe }}, but I’m still encountering the same issue.

How can I resolve this issue and successfully pass the data from my Django view to JavaScript in my template?

2

Answers


  1. I don’t whether your method is correct or not but according to me:

    1. Firstly try printing actual_data & predicted data in if statement (views.py).

    2. I would recommend using variables directly into your js script like:

      var actual = "{{actual_data}}";

      alert(actual)
      I hope this simple solution helps you.

    Login or Signup to reply.
  2. You use the |json_script template tag [Django-doc] for this:

    {{ actual_data|json_script:'actual_data' }}
    {{ predicted_data|json_script:'predicted_data' }}
    
    <select id="visualSelector" name="model" onchange="printSelectedValue(JSON.parse(document.getElementById('actual_data').textContent), JSON.parse(document.getElementById('predicted_data').textContent))">
        <option value="0">---</option>
        <option value="1">SCATTERPLOT</option>
        <option value="2">LINEPLOT</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search