1

I'm trying to access a Django placeholder, which is an array from the database, in a javascript script for use within three.js

I have the coord_x, coord_y and coord_z variables in views.py which comes from the database through:

cur.execute("""SELECT x FROM pc_processing.basesample""")
coord_x = cur.fetchall()
cur.execute("""SELECT y FROM pc_processing.basesample""")
coord_y = cur.fetchall()
cur.execute("""SELECT z FROM pc_processing.basesample """)
coord_z = cur.fetchall()

In my templates html (random testing numbers commented out, good for testing):

...
for (var i = 0 ; i < numpoints ; i++) {

    var x = {{coord_x}};
    var y = {{coord_x}};
    var z = {{coord_x}};

    // var x = Math.random() * (0 - 1) + 1
    // var z = Math.random() * (0 - 1) + 1
    // var y = Math.random() * (0 - 1) + 1

    var dotGeometry = new THREE.Geometry();
    dots.push(dotGeometry);
    dotGeometry.vertices.push(new THREE.Vector3(x, y, z));
    var dotMaterial = new THREE.PointsMaterial( { size: 3, sizeAttenuation: false, color: 0xFF0000 });
    var dot = new THREE.Points( dotGeometry, dotMaterial);
    scene.add(dot);
}
...

I'm guessing I need to somehow loop through the x,y,z variables?

Spatial Digger
  • 1,883
  • 1
  • 19
  • 37

1 Answers1

2

You can try like this:

send the variable through context like this in views.py:

context = { 'coord_x': 20, 'coord_y': 10, 'coord_z': 30}
return render(request, 'template.html', context)

And in the template attach the variables to window object:

<script>
window.x = "{{coord_x}}"
window.y = "{{coord_x}}"
window.z = "{{coord_x}}"
</script>

And use this in your JS file. if the variables are list then you have to loop through them:

var currX = x[i];
var currY = y[i];
var currZ = z[i];

dotGeometry.vertices.push(new THREE.Vector3(currX, currY, currZ));

Even better approach for this is to send these variables not as list, but dictionary. Like this in views.py:

context = { 'coordinates': [{'x':1, 'y':2, 'z':3}, {'x':1, 'y':2, 'z':4}] }
return render(request, 'template.html', context)

attach them in JS:

<script>
window.coordinates = "{{ coordinates }}";
</script>

and use it js like this:

coordinates.forEach(function(i){
...
dotGeometry.vertices.push(new THREE.Vector3(i.x, i.y, i.z));
...
}
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • I assume the context =... goes in the views.py? How would window.x work inside the loop I have setup? – Spatial Digger Dec 21 '18 at 02:03
  • ok, I think I'm getting it now, but the data 'context' is from three individual `cur.fetchall` rather than a dictionary, original post amended. – Spatial Digger Dec 21 '18 at 02:59
  • rather than using raw sql, why don't you use Django Models? If you do than you can pass the dictionary like mentioned in this SO answer: https://stackoverflow.com/a/7166134/2696165 – ruddra Dec 21 '18 at 04:33