将 Django 变量传递给 javascript

Pass Django variables to javascripts

我遇到了一个问题,我想将 django 变量传递给 javascripts 但我不能。

views.py

def dashboard_view(request):
    months_before = 5
    now = datetime.utcnow()
    from_datetime = now - relativedelta(months=months_before)
    modified_from_datetime = from_datetime.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    month = Btdetail.objects.filter(DatePur__gte=modified_from_datetime).count()
    return render(request, "dashboard.html", {'month': month})

我想将 值嵌入到 javascripts 数据

我的html脚本函数

<script>
    var xValues = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    new Chart("myChart3", {
    type: "line",
    data: {
        labels: xValues,
        datasets: [{
            data: [5,10,20,15,20,5,15,40,10,12,24,35],
            borderColor: "red",
            fill: false
            }]
        },
        options: {
            legend: {display: false}
        }
    });
</script>

实际上我想创建一个 Area 栏,一切都很好,但是 javascript 函数无法从 django 数据库中获取值,如果有其他方法可以做到这一点,请告诉我 [1]: https://i.stack.imgur.com/9bJzE.jpg

在您的 anypage.html<body> </body> 标签

<body>
   <p> text for example </p>
   <div> some divs </div>

   <script type="text/javascript">
       var month_count = {{ month }};
   </script>
</body>

它将在您的 anypage.html 上启动 month_count 变量,您可以在此 anypage.html

中将其与 javascript 一起使用
views.py
import json

        
def your_page(request):
    context = {
        "some_list": json.dumps([1,2,3]),
    }
    return render(request, "your_template.html", context)
javascript
<script>
    const some_list = JSON.parse(`{{some_list|safe}}`);
</script>