Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing Model in Python/Django Template

I'm trying to serialize some models that represent user settings in a django template. Here's what I'm doing:

<script type="text/javascript">
   var mutes = {{ user.appuser.mutes.all|safe }};
</script>

Instead of json, I get the following:

<script type="text/javascript">
   var mutes = [<Mute: Mute object>, <Mute: Mute object>];
</script>

I'm new to this and am clearly doing something wrong. Any help appreciated!

like image 463
threejeez Avatar asked May 10 '26 18:05

threejeez


2 Answers

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.

like image 60
gitaarik Avatar answered May 13 '26 07:05

gitaarik


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 }}');
like image 37
orokusaki Avatar answered May 13 '26 08:05

orokusaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!