Django将视图中的变量传递给模板javascript

时间:2018-04-07 15:07:04

标签: javascript python html django

说明

我有一个视图,每秒调用一次,从我项目的后端向 temperature.html 显示温度数据。为了实现它的目的,它需要一个变量,它将通过渲染传递给模板,我希望它被用作Javascript变量,以便更新我在模板中使用的画布规格来显示温度数据。

问题: 我的视图是以正确的间隔通过控制台调用的,所以这不是问题。但是,没有发生的是变量根本没有传递给模板。我试图让模板显示变量,以查看变量是否至少被发送到模板。答:它根本没有到达模板,可变输出“undefined”。我通过我的其他视图以这种方式传递表单,就像我尝试传递此变量一样,并且它正常工作。我不明白我的模板/视图错误的地方。我已经研究了至少6个小时试图找到解决方案,显然我没有找到与我需要的解决方案相关的解决方案。从我所看到的,似乎我传递我的变量的方式是正确的。但是,我对Django来说相对较新,所以我还不太了解这个问题。

相关代码 Views.py

的部分快照
def temperatureView(request):
    print("refresh..")
    #sen = Sensor()
    temperature = random.randint(1,100) #this is just an test variable
    print(temperature) #for debugging assistance

    return render(request,'temperature.html',{'Temperature':temperature})

参考 temperature.html

<html>
<head>
<script src="//cdn.rawgit.com/Mikhus/canvas-gauges/gh- 
pages/download/2.1.4/all/gauge.min.js"></script>
</head>
<body>
<div id = "test">
</div>
<canvas data-type="radial-gauge"
            data-width="300"
            data-height="300"
            data-units="&deg F"
            data-title="Temperature"
            data-value="0"
            data-min-value="0"
            data-max-value="100"
            data-major-ticks="0,10,20,30,40,50,60,70,80,90,100"
            data-minor-ticks="2"
            data-stroke-ticks="false"
            data-highlights='[
              { "from": 0, "to": 50, "color": 
                "rgba(0,255,0,.15)" },
              { "from": 50, "to": 100, "color": 
                "rgba(255,255,0,.15)" },
              { "from": 100, "to": 150, "color": 
                "rgba(255,30,0,.25)" },
              { "from": 150, "to": 200, "color": 
                "rgba(255,0,225,.25)" },
              { "from": 200, "to": 220, "color": 
                "rgba(0,0,255,.25)" }
            ]'
            data-color-plate="#222"
            data-color-major-ticks="#f5f5f5"
            data-color-minor-ticks="#ddd"
            data-color-title="#fff"
            data-color-units="#ccc"
            data-color-numbers="#eee"
            data-color-needle-start="rgba(240, 128, 128, 1)"
            data-color-needle-end="rgba(255, 160, 122, .9)"
            data-value-box="true"
            data-animation-rule="bounce"
            data-animation-duration="500"
            data-font-value="Led"
            data-animated-value="true"
></canvas>
<script>
   var gaugeElement = 
   document.getElementsByTagName('canvas')[0];
   var Current_Temperature = {{Temperature}} 
   <!-- Where I want passed variable to go -->
   document.write(Current_Temperature);
   gaugeElement.setAttribute('data-value', Current_Temperature) 
</script>
</body>
</html>

编辑:我认为我最好继续添加与之对应的其他视图和模板。

Views.py

的另一个片段
def home(request):
    return render(request,'home.html')

Home.html中

<!DOCTYPE html>
   <html>
   <title>Incubator Status Page</title>
   <head>
    {% load static %}
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"> 
    </script>
    <script src="//cdn.rawgit.com/Mikhus/canvas-gauges/gh- 
     pages/download/2.1.4/radial/gauge.min.js"></script>
    <script src="{% static 'canvas-gauges-master/gauge.min.js' %}"> 
    </script>
    <meta name="viewport" content="width=device-width, initial- 
     scale=1">
     <link rel="stylesheet" 
           href="https://www.w3schools.com/w3css/4/w3.css">
      <link rel="stylesheet" href="https://fonts.googleapis.com/css? 
            family=Lato">
      <link rel="stylesheet" 
             href="https://cdnjs.cloudflare.com/ajax/libs/font- 
                   awesome/4.7.0/css/font-awesome.min.css">
      <style>

       .incubatorTitle{
          text-align: center;
          font-size: 40px;
        }
       .incubatorVersion{
          text-align: center;
        }
       .test-button {
          border-radius: 4px;
          background-color: #f4511e;
          border: none;
          color: #FFFFFF;
          text-align: center;
          text-decoration: none;
          font-size: 28px;
          padding: 10px;
          width: 200px;
          height: 50px;
          transition: all 0.5s;
          cursor: pointer;
          }
         .test-button:hover {background-color: #3e8e41}
         .test-button:after {
           background-color: #3e8e41;
           box-shadow: 0 5px #666;
           transform: translateY(4px);
          }
         .button-space{
            margin:50px;
          }
         .content{
             margin-left: 200px;
             margin-right: 200px;
             width: 1500px;
             height: 3000px;
             background-color: red;
          }
        .temperature{
             position: fixed;
             bottom:0px;
             left:200px;
             height:300;
             width:300;
          }
         .humidity{
             position: fixed;
             bottom:0px;
             right:200px;
             height:300;
             width:300;
          }
         .hatch{
             background-repeat: no-repeat;
             background-size: 200px;
             position: fixed;
             text-align: center;
             top: 50px;
             right: 200px;
             width: 500px;
             height: 200px;
             border-color: yellow;
             border-width: 5px;
             border-style: solid;
             font-size: 20px;
             }
          .turn{
               background-repeat: no-repeat;
               background-size: 200px;
               position: fixed;
               text-align: center;
               top: 50px;
               left: 200px;
               width: 500px;
               height: 200px;
               border-color: yellow;
               border-width: 5px;
               border-style: solid;
               font-size: 20px;
               }

</style>
</body>
<body>

<div class="w3-top">
  <div class="w3-bar w3-black w3-card">
    <a class="w3-bar-item w3-button w3-padding-large w3-hide-medium 
      w3-hide-large w3-right" href="javascript:void(0)" 
      onclick="myFunction()" 
      title="Toggle Navigation Menu"><i class="fa fa-bars"></i></a>
        <h class = w3-bar w3-bar-title>Incubator Status Page</h6>
        <a href="{% url 'home' %}" class="w3-bar-item w3-button w3- 
           padding-large">Status</a>
    <a href="{% url 'IncubatorProgramming' %}" class="w3-bar-item w3- 
       button w3-padding-large w3-hide-small">Program Your 
       Incubator</a>
    <a href="{% url 'IncubatorSettingsPage' %}" class="w3-bar-item w3- 
       button w3-padding-large w3-hide-small">Settings</a>
    <a href="{% url 'IncubatorHelpPage' %}" class="w3-bar-item w3- 
       button w3-padding-large w3-hide-small">Help</a>
  </div>
</div>

<div id = "main" class = "content" >
<div class="hatch">
<p id="hatchTimer"></p>
    Time until Hatch
<script>
    var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();

    var x = setInterval(function() {

    $.ajax({
        type: "POST",
        url: "~/pythoncode.py",
        data: { param: text}
        }).done(function( o ) {
                {{InterfaceObject}}
            });
}, 1000);
</script>

</div>


<h1 class="incubatorTitle">Incubator Monitoring System</h1>
<h6 class = "incubatorVersion">Version 0.76</h6>
<div id = "temperaturRefreshable" class="temperature">
   {% include 'temperature.html' %}</div>
   <script>
   function temperatureDiv(){
    $.ajax({
   url: 'IncubatorTemperature',
   success: function() {
   $('temperaturRefreshable').html();
      setTimeout(temperatureDiv,1000);
   }
 });
    }
     // This reloads the <div> every 1 second.
    $(function(){
        temperatureDiv();
    });
</script>

<div class="humidity">
   <!-- this will get another guage as well -->
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

好的,看起来您正试图通过ajax调用温度视图来更新您的主视图。

这里有几个问题。在Django中,模板在加载到客户端浏览器之前呈现为服务器端。当你打电话

{% include 'temperature.html' %}

您只需要包含temperature.html并且不传递任何变量,因此Temperature将被定义为未定义,因为它只呈现一次服务器端

要实际获取更新值,您应该获取ajax请求的结果,然后将其写入文档。

试试这个:

$.ajax({
   url: 'IncubatorTemperature',
   success: function(data) {
     $('#temperaturRefreshable').html(data);
     setTimeout(temperatureDiv,1000);
   }
});

这是一个接近你想要的最小工作示例: https://files.fm/u/tknysjks

编辑: 已更改为更好的下载链接:https://files.fm/u/tknysjks