javascriptdjangodjango-viewsarea-chart

Pass Django variables to javascripts


I am stuck into a problem, I want to pass django variable to javascripts but I can't.

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})

I want to embed month value to javascripts data

my html script function is

<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>

actually I want to create a Area bar, all things are good but javascript functions cant get value from django database and if there is another way to do this please tell me [1]: https://i.sstatic.net/9bJzE.jpg


Solution

  • on your anypage.html inside <body> </body> tag

    <body>
       <p> text for example </p>
       <div> some divs </div>
    
       <script type="text/javascript">
           var month_count = {{ month }};
       </script>
    </body>
    

    it will initiate month_count variable on your anypage.html and you could use it with javascripts inside this anypage.html