skip to Main Content

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


  1. Chosen as BEST ANSWER

    I solved my problem with:

    models.py:

    class Link(models.Model):
        
        sequence = models.IntegerField(primary_key=False, default=increment_sequence_number)
        category = models.ForeignKey(CategoryField, on_delete=models.SET_NULL, null=True, blank=True, default=None)   
        link = models.CharField(max_length=300, null=True, blank=True, default=None)
        name = models.CharField(max_length=300, null=True, blank=True, default=None)
        description = models.CharField(max_length=300, null=True, blank=True, default=None)    
        image = models.ImageField(verbose_name='Path', blank=True, null=True, editable=True,upload_to='Logos/')
    

    views.py:

    from django.core import serializers
    
    def index(request):
        links = Link.objects.all().order_by('category','sequence')
        context = {
                   'links': serializers.serialize("json", links)
       }
    

    index.html

    `var linksData = JSON.parse('{{ links|escapejs }}');
                document.write('<p class="card-text">"'+String(linksData[1].fields.description)+'"</p>');`
    

  2. 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:

    1. Convert Django context data to JSON: In your views.py, serialize the links context data into JSON if it’s not already. For example:
    
    
        from django.shortcuts import render
        from django.core import serializers
        from .models import YourModel  # Assuming you have a model for `links`
        
        def index(request):
            links = YourModel.objects.all()  # Fetching your links from the database
            context = {
                'links': list(links.values('id', 'sequence', 'category', 'link', 'description', 'image'))  # Convert queryset to list of dictionaries
            }
            return render(request, 'index.html', context)
    
    
    1. 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:

    
    
        
            var linksData = JSON.parse('{{ links|escapejs }}');
        
            for(let j = 0; j "' + linksData[j].category + '"');
            }
        
    

    {{ 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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search