Django's quick and dirty - Passing data in JavaScript without AJAX

Hello, Khabrovites. For future students of the course "Web-developer in Python" we have prepared a translation of the material.






If we want to pass data from Django to JavaScript, we usually talk about APIs, serializers, JSON and AJAX calls. This is usually complicated by the presence of React or Angular on the front.





- โ€“ .





, Django :





from django.db import models


class SomeDataModel(models.Model):
    date = models.DateField(db_index=True)
    value = models.IntegerField()
      
      



TemplateView



:





<img alt="





from django.views.generic import TemplateView


class SomeTemplateView(TemplateView):
    template_name = 'some_template.html'
      
      



Chart.js, AJAX, API ..





some_template.html



, ( ):





<canvas id="chart"></canvas>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script>
window.onload = function () {
  var data = [48, -63, 81, 11, 70];
  var labels = ['January', 'February', 'March', 'April', 'May'];

  var config = {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        {
          label: 'A random dataset',
          backgroundColor: 'black',
          borderColor: 'lightblue',
          data: data,
          fill: false
        }
      ]
    },
    options: {
      responsive: true
    }
  };

  var ctx = document.getElementById('chart').getContext('2d');
  window.myLine = new Chart(ctx, config);
};
</script>
      
      



:





, , SomeDataModel



, :





from django.views.generic import TemplateView

from some_project.some_app.models import SomeDataModel


class SomeTemplateView(TemplateView):
    template_name = 'some_template.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['data'] = [
            {
                'id': obj.id,
                'value': obj.value,
                'date': obj.date.isoformat()
            }
            for obj in SomeDataModel.objects.all()
        ]

        return context
      
      



JavaScript Django:





<canvas id="chart"></canvas>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script>
window.onload = function () {
  // We render via Django template
  var data = [
    {% for item in data %}
      {{ item.value }},
    {% endfor %}
  ]

  // We render via Django template
  var labels = [
    {% for item in data %}
      "{{ item.date }}",
    {% endfor %}
  ]

  console.log(data);
  console.log(labels);

  var config = {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        {
          label: 'A random dataset',
          backgroundColor: 'black',
          borderColor: 'lightblue',
          data: data,
          fill: false
        }
      ]
    },
    options: {
      responsive: true
    }
  };

  var ctx = document.getElementById('chart').getContext('2d');
  window.myLine = new Chart(ctx, config);
};

</script>
      
      



, , , . JavaScript, JavaScript Django. JavaScript .js. JavaScript.





.





:





  1. json.dumps



    .





  2. <div>



    id



    data-json



    , JSON. 





  3. <div>



    JavaScript, data-json



    JSON.parse



    , .





, JavaScript Django, . 





AJAX.





, :





import json

from django.views.generic import TemplateView


class SomeTemplateView(TemplateView):
    template_name = 'some_template.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['data'] = json.dumps(
            [
                {
                    'id': obj.id,
                    'value': obj.value,
                    'date': obj.date.isoformat()
                }
                for obj in SomeDataModel.objects.all()
            ]
        )

        return context
      
      



JavaScript chart.js



.





some_template.html



:





{% load static %}

<div style="display: none" id="jsonData" data-json="{{ data }}"></div>

<canvas id="chart"></canvas>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script src="{% static 'chart.js' %}"></script>
      
      



div



. div



, . id



HTML-.





data-json



( - ) JSON.





, , :





function loadJson(selector) {
  return JSON.parse(document.querySelector(selector).getAttribute('data-json'));
}
      
      



chart.js



:





function loadJson(selector) {
  return JSON.parse(document.querySelector(selector).getAttribute('data-json'));
}

window.onload = function () {
  var jsonData = loadJson('#jsonData');

  var data = jsonData.map((item) => item.value);
  var labels = jsonData.map((item) => item.date);

  console.log(data);
  console.log(labels);

  var config = {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        {
          label: 'A random dataset',
          backgroundColor: 'black',
          borderColor: 'lightblue',
          data: data,
          fill: false
        }
      ]
    },
    options: {
      responsive: true
    }
  };

  var ctx = document.getElementById('chart').getContext('2d');
  window.myLine = new Chart(ctx, config);
};
      
      



, - . :





 

- , . JavaScript , . SPA ( React).






"Web- Python".



Demo day .








All Articles