我可以在django模板中渲染后添加或更新新变量

时间:2015-04-15 21:55:41

标签: python django django-forms django-templates django-views

我一直在尝试在第一次渲染之前在模板中添加或更新变量。我有一个发送POST请求的Ajax请求可以正常工作,但当我尝试将新变量destinations返回到同一页面/模板index.html时,它不会出现。

如何解决此问题?

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>

1 个答案:

答案 0 :(得分:1)

查看JsonResponse,您可以使用它将新变量作为json返回到您的ajax函数,然后可以使用该函数在模板中设置该变量。