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!
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.
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 }}');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With