Home > Blockchain >  Pass Django variables to javascripts
Pass Django variables to javascripts

Time:05-13

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.stack.imgur.com/9bJzE.jpg

CodePudding user response:

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

CodePudding user response:

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