I’m trying to access to my django context from my views.py to my index.html page but something wrong and I need help.
My context from django called in my html template is working fine with:
{% for i in links %}
<li><a>{{i.id}}; {{i.sequence}}; {{i.category}};{{i.link}}; {{i.description}}; {{i.image}}</a></li>
{% endfor %}
out of that give me:
2; 0; OUTILS DU QUOTIDIEN - DIVERS;https://safran.fabriq.tech/login; La solution tout-en-un pour le QRQC Digitalisé ! Détectez, escaladez, résolvez vos problèmes plus rapidement et améliorez votre performance.; Logos/Fabriq_0ER4lsy.png
3; 0; OUTILS DU QUOTIDIEN - DIVERS;https://improve.idhall.com/; Improve est la plateforme collaborative de Safran pour piloter toutes les initiatives de progrès du Groupe (de l'idée au projet d'amélioration).; Logos/Improve_lFlB5pY.png
4; 0; OUTILS DU QUOTIDIEN - DIVERS;https://portal.bi.group.safran/reports/powerbi/REPORTS/Safran%20Aircraft%20Engines/Develop/Innovation-Participative-SAE/IP-FULL-SAE?rs:Embed=true; PowerBI IP Safran Aircraft Engines.; Logos/Gestor_gVEU0RR.png
But my JS:
<script>
var linksData = '{{links}}';
for(let j=0;j< linksData.length;j++)
{
document.writeln('<p class="card-text">"'+String(linksData[j].category)+'"</p>');
}
</script>
Gives me:
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
"undefined"
...
My attempt was also with
var linksData = JSON.parse('{{links|escapejs}}');
but still not working and return nothing, could you help me please?
2
Answers
I solved my problem with:
models.py:
views.py:
index.html
The issue arises because you’re trying to directly pass a Django context variable, which is a Python object (in this case, probably a queryset or a list), into JavaScript in a stringified format. JavaScript does not automatically understand Python’s data structures, so you need to serialize the data properly to JSON before using it in your script.
Here’s how to resolve the issue:
Pass the serialized data correctly into your HTML: In your
index.html, you should pass the data from Django to JavaScript using
the |escapejs filter to avoid issues with special characters. Also,
use the JSON.stringify method properly to pass the context data into
your script.
Modify the script block like this:
{{ links|escapejs }}: This ensures that any special characters in the Django context are escaped properly when passed into JavaScript.
JSON.parse(): This parses the stringified data back into a JavaScript object (array in your case).
By converting your context data to JSON format and escaping it properly, JavaScript should be able to access and manipulate the data as expected.
Let me know if this works or if you're encountering further issues!