Karro Karro - 2 months ago 8
JSON Question

Django/Python : Using json.loads in the template

I am trying to use json.loads in my template in order to get a python's dictionnary. But unfortunately, i encounter the same error :

Could not parse the remainder: ' = json.loads(entry.saved_data)' from 'everyEntry = json.loads(entry.saved_data)'

Here is my code from the template :

{% for entry in entries %}

{{everyEntry = json.loads(entry.saved_data)}}
{{ everyEntry.items}}

{% for clef, valeura in headersLoop %}
{% for chiave, valore in everyEntry %}
{% if clef = chiave %}
<p>{{clef}} {{valore}}</p>
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}

An at this line :

{{everyEntry = json.loads(entry.saved_data)}}

the problem occurs.

How may i fix this ?

Thank you guys.

Answer Source

Thanks to bruno and Aniket, i found the solution.

First i created a method that returns a dict items such as bruno example :

class YourModel(models.Model):   

`def entry_saved_data(self):

return json.loads(self.saved_data)

Then i made this loop into my template.html :

                {%for entry in entries%}
                {%for cle, valeur in entry.all_form_entry_json%}
                {%for key, valor in headersLoop%}
                {%if key == cle%}

                 <td> {{valeur}}</td>

                {% endif %}
                {% endfor %}
                {% endfor %}                   
                {% endfor %}                    

It prints all the datas. But one small problem appears. It doesn't fill the array in a proper way. Nevertheless all the datas from all the forms are printed.