【问题标题】:Can I add or update a new variable after render in django template我可以在 django 模板中渲染后添加或更新新变量吗
【发布时间】:2015-06-22 02:05:11
【问题描述】:

我一直在尝试在第一次渲染之前在模板中添加或更新变量。我有一个 Ajax 请求,它发送一个工作正常的 POST 请求,但是当我尝试将新变量 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) 

寺庙索引.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>

【问题讨论】:

  • 你能添加你的模板代码吗?
  • 如果您通过 ajax 发送,您不想重新渲染所有页面。我建议你返回一个 JSON 响应,并通过模板中的 javascript 从这个 JSON 中获取数据。除非您刷新整个页面,否则您将无法获取 {{destinations }}。
  • 我宁愿不刷新页面。 @Celeo
  • 在此处发布您的 AJAX 请求代码

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


【解决方案1】:

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

【讨论】:

  • 谢谢我已经用 JsonResponse 解决了。将响应返回给 ajax 函数。并将其显示到模板中。再次感谢。
猜你喜欢
  • 2020-12-07
  • 2016-02-26
  • 2016-05-22
  • 1970-01-01
  • 2012-06-01
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
相关资源
最近更新 更多