Ludwing Van
Ludwing Van

Reputation: 43

Can I add or update a new variable after render in django template

I've been trying to add or update a variable in the templete before the first render. I have an Ajax request that sends a POST request which works fine, but when I tried to return the new variable, destinations, to the same page/template, index.html, it doesn't appear.

How do I fix this behavior?

view.py

def index(request):
    if request.method == 'POST':
        dayset = request.POST.get('the_point')
        dest = Destination(get_cons(dayset))
        destinations = dest.latlond()
        context = {'destinations': destinations}
        render(request, 'index.html', context)
    else:
        objan = Antennas(antenas)
        antposition = objan.getAntennas()
        context = {'antposition': antposition}
        return render(request, 'index.html', context) 

Temple index.html

<html>
<head>
<meta charset=utf-8 />
<title>DAKARmob</title>
{% load staticfiles %}
<script type="text/javascript" src="{% static "scripts/main.js" %}"></script>
<body>
<script type="text/javascript">
{% for pos in antposition %}
var marker = L.marker([{{pos.1}}, {{pos.2}}], {
  icon: L.mapbox.marker.icon({
      'marker-color': '#b9e841'
  }),
  draggable: false
}).on('click', onAnte);
antenas[{{pos.0}}] = [{{pos.1}}, {{pos.2}}];
cluster_ant.addLayer(marker);
{% endfor %}
map.addLayer(cluster_ant);

function onAnte(e) {
  var latl = this.getLatLng();
  var aux = [latl.lat,latl.lng];
  var result = getKeysForValue(antenas, aux);
  new_point(result[0]);


 function new_point(id) {
        console.log(id);
        $.ajax({
            url : "/", // the endpoint
            type : "POST", // http method
            data : { the_point : id }, // data sent with the post request
            success : function(res) {
                console.log("success"); // another sanity check
            }
        });

  }
  // OTHER FUNCTIONS FOR THE FUNCTION OF AJAX AND DJANGO 

</script>
<div style="position:absolute; top:900px; left:10px; ">
{{ destinations }}
</div>
</body>
</html>

Upvotes: 4

Views: 2176

Answers (1)

mcastle
mcastle

Reputation: 2982

Look at JsonResponse, which you can use to return the new variable as json to your ajax function, which can then be used to set that variable in your template.

Upvotes: 2

Related Questions