[Django]-Serializing Model in Python/Django Template

5👍

Generally it’s not a very good idea to directly serialize a django model for usage in the frontend, mainly because of security. What if there’s data on your model that your users aren’t allowed to read?

For this reason, you would usually create the objects in javascript manually:

var objects = [];

{% for model in models %}
    objects[] = {
        name: {{ model.name }},
        date: {{ model.date }},
        // etc.
    };
{% endfor %}

This way, only the data you explicitly define in your template get into the javascript. If your model changes in the future and gets sensitive data added, it won’t appear in the javascript objects.

2👍

You can use Django’s built-in serialization, or use just the serialization functionality from Django Rest Framework. I find Django Rest Framework to be a better option, even for simple tasks, because it’s very flexible and requires less overhead in your own code.

Either way, you’ll need to use JSON.parse, like so:

var mutes = JSON.parse('{{ serialized_value }}');

Leave a comment